gpt4 book ai didi

r - 在 r 中合并具有相似内容的列表项?

转载 作者:行者123 更新时间:2023-12-05 02:37:38 25 4
gpt4 key购买 nike

我有列表 v:

v <- list(c("12", "1"), c("12", "2"), c("12", "3"), c("13", "1"), c("22", "3"), c("30", "4"))

我需要合并这个列表中共享相同第一个数字的行,方法是连接用逗号分隔的第二个数字,这样生成的列表 w 就像这样:

w <- list(c("12", "1,2,3"), c("13", "1"), c("22", "3"), c("30", "4"))

> vv <- do.call(rbind.data.frame, v)
> names(vv) <- c("v1", "v2")
> vv
v1 v2
1 12 1
2 12 2
3 12 3
4 13 1
5 22 3
6 30 4
> vvv <-vv %>%
+ group_by(v1) %>%
+ summarise(v3 = paste0(v2, collapse = ","))
> vvv
# A tibble: 4 x 2
v1 v3
<fct> <chr>
1 12 1,2,3
2 13 1
3 22 3
4 30 4
> w <- as.list(as.data.frame(t(vvv)))
> w
$V1
v1 v3
12 1,2,3
Levels: 1,2,3 12

$V2
v1 v3
13 1
Levels: 1 13

$V3
v1 v3
22 3
Levels: 22 3

$V4
v1 v3
30 4
Levels: 30 4

> w <- lapply(as.list(1:dim(vvv)[1]), function(x) as.character(vvv[x[1],]))
> w
[[1]]
[1] "1" "1,2,3"

[[2]]
[1] "2" "1"

[[3]]
[1] "3" "3"

[[4]]
[1] "4" "4"

> w <- base::lapply(as.list(1:dim(vvv)[1]), function(x) as.character(vvv[x[1],]))
> w
[[1]]
[1] "1" "1,2,3"

[[2]]
[1] "2" "1"

[[3]]
[1] "3" "3"

[[4]]
[1] "4" "4"

最佳答案

使用应用函数族的基本 R 选项

#get 1st value from each list
group_values <- sapply(v, `[[`, 1)

#For each unique group value combine all the other values in one
#comma separated string
Map(c, unique(group_values),
tapply(v, group_values, function(x)
toString(unlist(sapply(x, tail, -1)))))

#$`12`
#[1] "12" "1, 2, 3"

#$`13`
#[1] "13" "1"

#$`22`
#[1] "22" "3"

#$`30`
#[1] "30" "4"

关于r - 在 r 中合并具有相似内容的列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69906872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com