r - 如何使用带公式作为字符串的dcast.data.table

标签 r data.table reshape

我想使用带有列名作为字符串的公式的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/

相关文章:

r - 按组计算相对于开始日期的差异

r - 从 R 中的 data.table 按组计算平均每月总数

python - 将 3D numpy 矩阵 reshape 为 2D numpy 矩阵,保持行位置

list - 在 R 列表中插入元素

html - R&Knitr html输出: Create collapsing and expanding header

r - stringr:正则表达式,用于匹配和提取包含相同子字符串的字符串(包括唯一子字符串)

r - 按年份对 data.table 结果进行分组的有效方法

使用完整的二进制列 reshape 数据

r - 使用 plyr : melt/cast vs. ddply 修复基于 reshape 的习惯

r - 使用 lpSolve 在整数规划中实现附加约束变量