I have data
Score <- c(9.6 ,7.8,6.9,9.6,NA,NA,9.3,9.3,11.1,6.7,5.9,10.4,12.2,6.5,10.1,8.5,7.0,11.2,0.6,8.0)
CNTRL <- c(rep(12,4), rep(14,4), rep(16,4), rep(18,4), rep(20,2), rep(22,2))
SERV <- c(rep(10, 5), rep(15,2), rep(20,13))
LOS <- c(rep(1,5), rep(0,15))
RESP <- c(rep(0,10), rep(1,10))
DataAnalysis <- data.table(Score, CNTRL, SERV, LOS, RESP)
DataAnalysis <- DataAnalysis[, lapply(.SD, as.character), by = Score]
If I find mean and sd of Score by CNTRL
DataAnalysis[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE)), by = CNTRL]
How I apply a list for all of variables at once CNTRL, SERV, LOS, RESP, so it returns a list of 4 variables
lapply(names(DataAnalysis)[-1], function(x) x[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE))],by = names(DataAnalysis)[-1])
I did something wrong, I couldn't get it right.
This is result
[[1]]
CNTRL Score.mean Score.sd
1: 12 8.475 1.350000
2: 14 9.300 0.000000
3: 16 8.525 2.605603
4: 18 9.325 2.417126
5: 20 9.100 2.969848
6: 22 4.300 5.232590
[[2]]
SERV Score.mean Score.sd
1: 10 8.475000 1.350000
2: 15 9.300000 NA
3: 20 8.269231 3.065503
[[3]]
LOS Score.mean Score.sd
1: 0 8.342857 2.958096
2: 1 8.475000 1.350000
[[4]]
RESP Score.mean Score.sd
1: 0 8.7875 1.516045
2: 1 8.0400 3.345046
更正的代码
lapply(names(DataAnalysis)[-1], function(x) DataAnalysis[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE)),by = x])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.