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

标签 r dplyr data.table tidyverse

我是 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/

相关文章:

r - 从数据框中仅提取数字列

r - dplyr:如何使用 mutate 按列索引而不是列名称引用列?

在 R 中的 data.table 中用 0 替换所有 NA

r - 使用 r 中的 data.table 创建具有不同规则的列

r - R 中特定列的总和 NA

r - 如何将表格添加到ggplot?

regex - 使用gsub删除多个空格和尾部空格

r - 按两列分组并汇总多列

r - sparklyr - 在 Apache Spark Join 中包含空值

r - 如何在 data.table 上使用 sep2 = ""