【问题标题】:Melt a data.table with a list data type (get lists of values in one col for each unique value in another col)熔化具有列表数据类型的 data.table(获取一个列中的值列表,以获得另一个列中的每个唯一值)
【发布时间】:2018-06-15 16:49:36
【问题描述】:

我有一个看起来像这样的data.table

dt <- data.table(
       cbind(
          id = c( 1, 1, 2, 2, 3, 3, 3 ),
          y = c( 'a', 'b', 'c', 'd', 'e', 'f', 'g' )
       )
);

我想将其转换为如下所示的data.table

   id   y.list
1:  1    list( a, b )
2:  2    list( c, d )
3:  3    list( e, f, g )

上面的list 可以是任何容器,即vector、简单的c,或者可以在以后迭代的任何其他容器。感谢您的任何建议!

【问题讨论】:

  • 你不需要cbind...你可以直接去dt &lt;- data.table(id = ...)

标签: r data.table


【解决方案1】:
> dt = dt[, list(list(y)), by = id]
> dt
   id    V1
1:  1   a,b
2:  2   c,d
3:  3 e,f,g
> class(dt[1, V1])
[1] "list"

This 有帮助的 SO 问题提供了有关 data.table 对象中列表的一些背景信息。特别是,this 响应提到您需要使用list(list()) 公式,因为对于list() 的单个实例,data.table 将使用它来查找要通过引用分配给列的值。

扩展

## For all unique values, you can use:
dt = dt[, .(.(unique(y))), by = id] # all unique values

# If you want to write a list column to file. 
# Default separator within the column is |  
# You can specify otherwise with sep2 argument (must be of length 3):
fwrite(dt, Out_FN, sep="\t", sep2 = c("", ";", ""))

【讨论】:

  • dt[, .(.(y)), by = id] 减少打字次数。
猜你喜欢
  • 2020-03-10
  • 2019-10-29
  • 2023-02-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多