我有以下

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")


不幸的是,我在示例中错过了这一行

dt <- data.table(anid, agroup, anothergroup, avalue)


基本上,我想使用一个函数来创建mygoal列的值,但不幸的是我卡住了。我想使用类似这样的方式创建mygoal列

dt[, mygoal:= lapply(...)]


进入函数的列数可以变化,但是尽管我知道它们,但是必须有可能将列作为字符向量提供给函数。在上面的示例中,列“ agroup”和“ anothergroup”用于创建列“ mygoal”的值。

再次感谢任何提示

汤姆

最佳答案

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

关于r - 串联列名和列值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25349171/

10-12 20:32