我想使用带有列名作为字符串的公式的data.table的强制转换
我的 table :
c1 c2 c3
1 A 1
1 B 2
1 C 3
2 A1 1
2 B1 2
2 C1 3
我想得到结果:
c1 1 2 3
1 A B C
2 A1 B1 C1
我可以用命令来做
dcast.data.table(dt, c1 ~ c3, value.var = "c2")
但是我想在具有c1列名称的参数作为字符串的函数中运行dcast。例如
f1 <- function(d, col_name1, col_name2, col_name3) {
dcast.data.table(d, col_name1 ~ col_name3, value.var = col_name2)
}
所以我会打电话
f1(dt, "c1", "c2", "c3")
希望任何人都能提供帮助!
最佳答案
dcast
也接受公式作为字符串。
f1 <- function(d, col_name1, col_name2, col_name3) {
dcast.data.table(d, paste(col_name1, "~", col_name3), value.var = col_name2)
}
f1(dt, "c1", "c2", "c3")
# c1 1 2 3
# 1: 1 A B C
# 2: 2 A1 B1 C1
请注意,您无需加载
reshape2
,也可以直接使用dcast
代替1.9.5+版本中的dcast.data.table
。
关于r - 如何使用带公式作为字符串的dcast.data.table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29297180/