我尝试将 Age 变量拆分为多个区间,计算平均值、sd 和区间的计数,然后将每个区间的输出保存在向量中,然后将这些向量组合到一个数据框中,对于每个区间,我可以简单地取值。
我已经这样做了:
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)
}
Run Code Online (Sandbox Code Playgroud)
这是我从我的代码中得到的:
i3
[1,] 45.22727
[2,] 13.11818
Run Code Online (Sandbox Code Playgroud)
我什至没有尝试包括计数,因为我没有机会锻炼解决方案。
非常感谢你的帮助!
这不是一个函数,但它实现了你想要的:
# sample data
df <- data.frame(
age = runif(100, min = 10, max = 100)
)
# trying to first define the categories and then calculate the descriptive statistics
# edit: I used @thelatemail suggestion from the comments to simplify the code
df %>%
group_by(category = cut(age, c(0,30,40,50,60,Inf), labels=paste0("i",1:5))) %>%
summarise(
mean = mean(age),
sd = sd(age),
count = n()
)
Run Code Online (Sandbox Code Playgroud)