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
I use next code for grouping by id:
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]
to get something like this:
id date1 charval
1: 1 2009-01-02 aa;vv;ss
2: 2 2009-01-05 a;b;c;d
but in real I see next result:
id date1 charval
1: 1 NA aa
2: 2 NA a
1) I dont understand why paste doesnt work 2) I dont understand why mean(date1) doesnt work because for example next code works fine:
mean(dt2$date1)
[1] "2009-01-04"