2016-07-08 76 views
0

lapply我有數據lapply在data.table

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] 

如果我發現是指由CNTRL

DataAnalysis[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE)), by = CNTRL] 

得分的SD和我如何在一次CNTRL應用列表中的所有的變量, SERV,LOS,RESP,那麼它將返回4個變量

lapply(names(DataAnalysis)[-1], function(x) x[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE))],by = names(DataAnalysis)[-1]) 

我做錯事的名單,我無法得到它的權利。

這是結果

[[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 

回答

4

更正代碼

lapply(names(DataAnalysis)[-1], function(x) DataAnalysis[,list (mean = mean(Score, na.rm = TRUE),sd = sd(Score, na.rm = TRUE)),by = x]) 
+0

感謝,首先我沒有改變DataAnalysis,然後通過改變,繼續做做了,不能firgure – BIN