我有一个数据表test:

id key
1 2365
1 2365
1 3709
2 6734
2 1908
2 4523

我想使用data.table包将唯一的key个值乘以id聚合到向量中.

预期输出:

id key_array
1 "2365", "3709"
2 "6734", "1908", "4523"

所以,这应该像array_agg个sql函数一样工作.

I tried:
res <- test[, list(key_array = paste(unique(key), collapse = ", ")), by = "id"], but I get just a string. But I need to have opportunity to find the length of each vector and operate with its certain elements (find the intersection of two vectors for example).

推荐答案

1. Base R

这是aggregate一行.

x <- 'id    key
1   2365
1   2365
1   3709
2   6734
2   1908
2   4523'
test <- read.table(textConnection(x), header = TRUE)

aggregate(key ~ id, test, \(x) c(unique(x)))
#>   id              key
#> 1  1       2365, 3709
#> 2  2 6734, 1908, 4523

reprex package(v2.0.1)于2022年6月14日创建

但如果user@Chris's comment是正确的,那么正确的解决方案如下.

aggregate(key ~ id, test, \(x) paste(unique(x), collapse = ", "))

请注意,c(unique(x))as.character(c(unique(x)))都将输出一个列表列,因此后一种解决方案无论如何都是正确的.


2. Package data.table

再一次,一行.

输出是一个列表列,每个列表成员都是一个整数向量.要保留为整数,请使用

list(unique(key))

相反

suppressPackageStartupMessages(library(data.table))

res <- setDT(test)[, .(key_array = list(as.character(unique(key)))), by = id]
res
#>    id      key_array
#> 1:  1      2365,3709
#> 2:  2 6734,1908,4523

str(res)
#> Classes 'data.table' and 'data.frame':   2 obs. of  2 variables:
#>  $ id       : int  1 2
#>  $ key_array:List of 2
#>   ..$ : chr  "2365" "3709"
#>   ..$ : chr  "6734" "1908" "4523"
#>  - attr(*, ".internal.selfref")=<externalptr>

reprex package(v2.0.1)于2022年6月14日创建

然后,为了访问向量,使用两个提取器,一个用于提取列,另一个用于提取向量.

res$key_array[[1]]
#> [1] "2365" "3709"
res$key_array[[2]]
#> [1] "6734" "1908" "4523"

reprex package(v2.0.1)于2022年6月14日创建


3. dplyr solution

id分组并将唯一字符串折叠为一个字符串.

suppressPackageStartupMessages(library(dplyr))

test %>%
  group_by(id) %>%
  summarise(key_array = paste(unique(key), collapse = ", "))
#> # A tibble: 2 × 2
#>      id key_array  
#>   <int> <chr>           
#> 1     1 2365, 3709      
#> 2     2 6734, 1908, 4523

reprex package(v2.0.1)于2022年6月14日创建

R相关问答推荐

在之前合并的数据.tables中分配新列后.internal.selfref无效

如何通过Exams2黑板对非整数字的问题进行评分

使用格式化程序自定义hc_tooltip以添加textColor删除了我的标记并try 将它们带回失败

使用R中的gt对R中的html rmarkdown文件进行条件格式设置表的单元格

对lme 4对象运行summary()时出错(diag中的错误(from,names = RST):对象unpackedMatrix_diag_get找不到)

基于现有类创建类的打印方法(即,打印tibles更长时间)

根据R中的另一个日期从多列中 Select 最近的日期和相应的结果

如何在R中添加截止点到ROC曲线图?

将包含卷的底部25%的组拆分为2行

矩阵的堆叠条形图,条形图上有数字作为标签

使用Facet_WRAP时更改框图中线的 colored颜色

如何通过ggplot2添加短轴和删除长轴?

派生程序包| ;无法检索';return()';的正文

如何计算R glm probit中的线性预测因子?

将数据集旋转到长格式,用于遵循特定名称模式的所有变量对

从线的交点创建面

避免在图例中显示VLINS组

访问数据帧中未定义的列时出现R错误

按组使用dummy r获取高于标准的行的平均值

在鼠标悬停时使用Plotly更改geom_point大小