i have the following
library(data.table)
anid <- c(1,2,3,4)
agroup <- c("m", "m", "f", "f")
anothergroup <- c("a","c", NA, "c")
avalue <- c(11, 6, 17, 3)
mygoal <- c("agroup:m_anothergroup:a","agroup:m_anothergroup:c","agroup:f_anothergroup:NA","agroup:f_anothergroup:c")
unfortunately i missed this line in my example
dt <- data.table(anid, agroup, anothergroup, avalue)
Basically I want to create the values of the column mygoal using a function, but unfortunately im stuck. I want to create the column mygoal using something similar like this
dt[, mygoal:= lapply(...)]
The number of columns that go into the function can vary, but nevertheless I know them but it has to be possible to provide the columns to the function as character vector. In the above example the columns "agroup" and "anothergroup" are used to create values for the column "mygoal".
Once again, any hint is appreciated
Tom
cols <- c("agroup", "anothergroup")
DT[, mygoal := do.call(paste,
c(lapply(cols, function(x) paste(x, get(x), sep=":")),
sep="_"))]
# anid agroup anothergroup avalue mygoal
#1: 1 m a 11 agroup:m_anothergroup:a
#2: 2 m c 6 agroup:m_anothergroup:c
#3: 3 f NA 17 agroup:f_anothergroup:NA
#4: 4 f c 3 agroup:f_anothergroup:c
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments