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日创建