gpt4 book ai didi

r - 数据争论 : Aggregating by group sequentially reducing

转载 作者:行者123 更新时间:2023-12-01 13:14:59 25 4
gpt4 key购买 nike

我是 R 的新手。我需要按顺序按组聚合数据。我正在添加我的数据框。前两列给出了数据,我必须改变第三列。

df <- data.frame(id = c(rep("a",3), rep("b",2), rep("c", 4)),
value = c("x", "z", "p", "q", "q", "m", "n", "x", "y"),
reqd = c("x,z,p", "z,p", "p", "q,q","q", "m,n,x,y", "n,x,y", "x,y", "y"))

我按组汇总了,但不正确

df_2 <- df[,1:2]  %>% 
group_by(id) %>%
mutate(reqd2 = paste(value, collapse = ","))

最佳答案

我们可以group_by id 并在当前row_number 和每个组中的总行数之间创建一个序列,并连接相应的toString

library(dplyr)
library(tidyr)

df %>%
group_by(id) %>%
mutate(reqd1 = map2_chr(row_number(),n(),~toString(value[.x:.y])))

# id value reqd reqd1
# <fct> <fct> <fct> <chr>
#1 a x x,z,p x, z, p
#2 a z z,p z, p
#3 a p p p
#4 b q q,q q, q
#5 b q q q
#6 c m m,n,x,y m, n, x, y
#7 c n n,x,y n, x, y
#8 c x x,y x, y
#9 c y y y

我们也可以仅使用带有 ave

的基础 R 来做到这一点
with(df, ave(value, id, FUN = function(x) 
mapply(function(i, j) toString(x[i:j]), seq_along(x), length(x))))

#[1] "x, z, p" "z, p" "p" "q, q" "q" "m, n, x, y" "n, x, y" "x, y" "y"

关于r - 数据争论 : Aggregating by group sequentially reducing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953290/

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