数据表聚合和使用toString()

时间:2017-09-22 19:05:40

标签: r data.table

我试图创建一个函数,我在一个列的基础上聚合数据表值,但是我无法在列名称的toString()中传递参数。以下示例可以更好地显示它:

t1 <- data.table(P = c("a", "b", "c", "d", "a", "b"), Q = 
c("1","2","3","4","5","6"))

t1[ ,toString(Q), by = P] # this works
t1[ ,toString(colnames(t1)[2]), by = P] #  this does not give me the desired result

我得到以下结果:

   P V1
1: a  Q
2: b  Q
3: c  Q
4: d  Q

与预期相比:

   P   V1
1: a 1, 5
2: b 2, 6
3: c    3
4: d    4

我尝试使用noquotes()删除引号,但对我来说没有任何效果。 任何人都可以指出我可能犯错的地方吗?

1 个答案:

答案 0 :(得分:2)

我们可以使用get返回值

t1[ , toString(get(colnames(t1)[2])), by = P]
#   P   V1
#1: a 1, 5
#2: b 2, 6
#3: c    3
#4: d    4

eval/as.symbol

t1[, toString(eval(as.symbol(names(t1)[2]))), by = P]

或者标准方式是在.SDcols

中指定
t1[, toString(.SD[[1]]), by = P, .SDcols = names(t1)[2]]