在 data.table 中每组返回多行

问题描述 投票:0回答:0

是否可以在

data.table
中的分组命令中每组返回多行?在
dplyr
中,这是用
reframe
完成的:

y <- c("a", "b", "d", "f")
df <- tibble(
  g = c(1, 1, 1, 2, 2, 2, 2),
  x = c("e", "a", "b", "c", "f", "d", "a")
)

library(dplyr)
df %>%
  reframe(x = intersect(x, y), .by = g)
#   g x
# 1 1 a
# 2 1 b
# 3 2 f
# 4 2 d
# 5 2 a

data.table
中,这会返回一个错误:

library(data.table)
dt <- setDT(df)
dt[, x := intersect(x, y), g]

[.data.table
(df, ,
:=
(x, intersect(x, y)), g) 中的错误:
提供了 2 件物品,分配给“x”列中尺寸为 3 的第 1 组。 RHS 长度必须为 1(单个值可以)或匹配 LHS 长度正好。如果你想“回收”RHS,请使用 rep() 明确地向您的代码读者明确说明此意图。

无论如何要得到一个

data.table
相当于
reframe

r data.table grouping
© www.soinside.com 2019 - 2024. All rights reserved.