问题描述
我想使用具有列名作为字符串的公式的data.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 ABC
2 A1 B1 C1
我可以使用命令
dcast.data.table(dt,c1 〜c3,value.var = c2)
但是我想在具有c1列名参数的函数中运行dcast串。例如
f1<-函数(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 dcast.data.table(d,paste(col_name1,〜,col_name3),value.var = col_name2)
}
f1(dt, c1, c2, c3)
#c1 1 2 3
#1:1 ABC
#2:2 A1 B1 C1
请注意,您不必加载 reshape2
而且您也可以直接使用 dcast
代替版本1.9.5 +
I want to use cast for a data.table with formula with name of columns as string
My table:
c1 c2 c3
1 A 1
1 B 2
1 C 3
2 A1 1
2 B1 2
2 C1 3
I want to have result:
c1 1 2 3
1 A B C
2 A1 B1 C1
I could do it with command
dcast.data.table(dt, c1 ~ c3, value.var = "c2")
But I want to run dcast in a function which has param of c1 column name as string. For example
f1 <- function(d, col_name1, col_name2, col_name3) {
dcast.data.table(d, col_name1 ~ col_name3, value.var = col_name2)
}
So I would call
f1(dt, "c1", "c2", "c3")
Hope anyone can help!
dcast
accepts formula as a string as well.
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
Note that you don't have to load reshape2
and you can also directly use just dcast
instead of dcast.data.table
from versions 1.9.5+
这篇关于如何使用带公式作为字符串的dcast.data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!