gpt4 book ai didi

r - 第 1 组的唯一值,然后是第 1 组和第 2 组,依此类推

转载 作者:行者123 更新时间:2023-12-01 07:04:07 27 4
gpt4 key购买 nike

我有一个包含 5 个不同组的数据框:

   id group
1 L1 1
2 L2 1
3 L1 2
4 L3 2
5 L4 2
6 L3 3
7 L5 3
8 L6 3
9 L1 4
10 L4 4
11 L2 5

我想知道是否有可能获得唯一的 id从第 1 组开始,第 1 组和第 2 组,第 1 组、第 2 组和第 3 组等等,没有循环。我正在用 dplyr 寻找方法或 data.table包裹。

预期成绩 :
    group      id
1 1 c("L1", "L2")
2 1,2 c("L1", "L2", "L3", "L4")
3 1,2,3 c("L1", "L2", "L3", "L4", "L5")
4 1,2,3,4 c("L1", "L2", "L3", "L4", "L5")
5 1,2,3,4,5 c("L1", "L2", "L3", "L4", "L5")

数据 :
structure(list(id = c("L1", "L2", "L1", "L3", "L4", "L3", "L5", 
"L6", "L1", "L4", "L2"), group = structure(c(1L, 1L, 2L, 2L,
2L, 3L, 3L, 3L, 4L, 4L, 5L), .Label = c("1", "2", "3", "4", "5"
), class = "factor")), .Names = c("id", "group"), row.names = c(NA,
-11L), class = "data.frame")

最佳答案

使用基础 R,您可以执行以下操作:

# create the "growing" sets of groups
combi_groups <- lapply(seq_along(unique(df$group)), function(i) unique(df$group)[1:i])

# get the unique ID for each set of groups
uniq_ID <- setNames(lapply(combi_groups, function(x) unique(df$id[df$group %in% x])),
sapply(combi_groups, paste, collapse=","))

# $`1`
# [1] "L1" "L2"

# $`1,2`
# [1] "L1" "L2" "L3" "L4"

# $`1,2,3`
# [1] "L1" "L2" "L3" "L4" "L5" "L6"

# $`1,2,3,4`
# [1] "L1" "L2" "L3" "L4" "L5" "L6"

# $`1,2,3,4,5`
# [1] "L1" "L2" "L3" "L4" "L5" "L6"

如果您想按照预期的输出进行格式化:
data.frame(group=sapply(combi_groups, paste, collapse=", "), id=sapply(uniq_ID, function(x) paste0("c(", paste0("\"", x, "\"", collapse=", "), ")")))
# group id
#1 1 c("L1", "L2")
#2 1, 2 c("L1", "L2", "L3", "L4")
#3 1, 2, 3 c("L1", "L2", "L3", "L4", "L5", "L6")
#4 1, 2, 3, 4 c("L1", "L2", "L3", "L4", "L5", "L6")
#5 1, 2, 3, 4, 5 c("L1", "L2", "L3", "L4", "L5", "L6")

格式化的另一种可能性:
data.frame(group=rep(names(uniq_ID), sapply(uniq_ID, length)), id=unlist(uniq_ID))

或者,如果您想拥有 uniq_ID在列中:
library(data.table)
data.table(group=sapply(combi_groups, paste, collapse=", "), id=uniq_ID)
# group id
#1: 1 L1,L2
#2: 1, 2 L1,L2,L3,L4
#3: 1, 2, 3 L1,L2,L3,L4,L5,L6
#4: 1, 2, 3, 4 L1,L2,L3,L4,L5,L6
#5: 1, 2, 3, 4, 5 L1,L2,L3,L4,L5,L6

data.table(group=sapply(combi_groups, paste, collapse=", "), id=uniq_ID)[2, id]
[[1]]
[1] "L1" "L2" "L3" "L4"

关于r - 第 1 组的唯一值,然后是第 1 组和第 2 组,依此类推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866137/

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