【问题标题】:converting two column data table to data table with colnames from one column and values from the other [duplicate]将两列数据表转换为具有来自一列的列名和来自另一列的值的数据表[重复]
【发布时间】:2017-03-08 17:57:55
【问题描述】:

有没有更优雅的方式来执行tdt,如下例所示,仅使用 base 或 data.table 函数和操作?

library(data.table)
dt <- data.table(a = letters[1:5], b = 1:5)
dt
# a b
# 1: a 1
# 2: b 2
# 3: c 3
# 4: d 4
# 5: e 5
tdt <- data.table(t(matrix(dt$b, dimnames = list(dt$a, NULL))))
tdt
# a b c d e
# 1: 1 2 3 4 5

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我们可以使用dcast

    dcast(dt[, rn := 1], rn~a, value.var = "b")[, rn := NULL][]
    #   a b c d e
    #1: 1 2 3 4 5
    

    或者

    setDT(setNames(as.list(dt$b), dt$a))[]
    #   a b c d e
    #1: 1 2 3 4 5
    

    或者

    dt[, setNames(as.list(b),a )]
    

    【讨论】:

    • 美丽。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2012-04-27
    • 2020-10-12
    相关资源
    最近更新 更多