library(data.table)
library(lubridate)
x1 <- c(20090101, "2009-01-02", "2009 01 03", "2009-1-4",
"2009-1, 5", "Created on 2009 1 6", "200901 !!! 07")
dt2 <- data.table(id = c(1,1,1,2,2,2,2), date1 = ymd(x1), charval = c("aa","vv","ss","a","b","c","d"))
id date1 charval
1: 1 2009-01-01 aa
2: 1 2009-01-02 vv
3: 1 2009-01-03 ss
4: 2 2009-01-04 a
5: 2 2009-01-05 b
6: 2 2009-01-06 c
7: 2 2009-01-07 d
我用下面的代碼通過ID分組:[R崩潰多行到1行使用特定的功能,日期和字符列
dt3 <- dt2[, Map(function(x,y) ifelse(x != "paste", get(x)(y, na.rm = TRUE), paste(y, sep = ";")),
setNames(c("mean", "paste"), names(.SD)), .SD), by = id]
得到的東西是這樣的:
id date1 charval
1: 1 2009-01-02 aa;vv;ss
2: 2 2009-01-05 a;b;c;d
但實際上我看到下一個結果:
id date1 charval
1: 1 NA aa
2: 2 NA a
1)我不明白爲什麼粘貼不工作 2)我不明白爲什麼平均值(日期1)不工作 因爲例如下面的代碼工作正常:
mean(dt2$date1)
[1] "2009-01-04"