Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206235

How to build a function in R that splits variables into intervals and calculate mean, sd and a count for the intervals

$
0
0

I try to split a Age variable into intervals, calculate mean, sd and a count for the intervals then save the outputs for every interval in a vector and then combine these vectors to a data frame where for every interval I can simply take the values.

I've done this:

intervals <- function(g){
  i1 <- c()
  i2 <- c()
  i3 <- c()
  i4 <- c()
  i5 <- c()
  if(g <= 30){
    i1 <- c(mean(g), sd(g))
    df <- cbind(i1)
  }else if(g > 30 & g <= 40){
      i2 <- c(mean(g), sd(g))
      df <- cbind(i2)
  }else if(g > 40 & g <= 50){
      i3 <- c(mean(g), sd(g))
      df <- cbind(i3)
  }else if(i >50 & i <= 60){
      i4 <- c(mean(g), sd(g))
      df <- cbind(i4)
  }else if(g > 60){
      i5 <- c(mean(g), sd(g))
      df <- cbind(i5)
  }else{
 } 
return(df)
}

This is what I get from my code:

           i3
[1,] 45.22727
[2,] 13.11818

I havent even tried to include the count because I had no chance to workout a solution.

Thank you so much for your help!


Viewing all articles
Browse latest Browse all 206235

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>