首页 > 解决方案 > 如何折叠具有相同标识符的行并保留非空列值?

问题描述

我有一个表(经过一些初始处理)有多行具有相同的主标识符但具有不同的列值(0或值> 0)。

带有主标识符“produce”的示例表

df = data.frame(produce = c("apples","apples", "bananas","bananas"),
                grocery1=c(0,1,1,1),
                grocery2=c(1,0,1,1),
                grocery3=c(0,0,1,1))


###########################

> df
  produce grocery1 grocery2 grocery3
1  apples        0        1        0
2  apples        1        0        0
3 bananas        1        1        1
4 bananas        1        1        1

我想折叠(或合并?)具有相同标识符的行并在每列中保留非空(此处为任何非零值)值

示例所需的输出

 shopping grocery1 grocery2 grocery3
1   apples        1        1        0
2  bananas        1        1        1

tidyverse中是否有我缺少的简单功能或管道可以处理这个问题?

标签: rdplyrtidyr

解决方案


使用基础 Raggregate我们可以做

aggregate(.~produce, df, function(x) +any(x > 0))

#  produce grocery1 grocery2 grocery3
#1  apples        1        1        0
#2 bananas        1        1        1

或使用dplyr

library(dplyr)
df %>%
  group_by(produce) %>%
  summarise_all(~+any(. > 0))

#  produce grocery1 grocery2 grocery3
#  <fct>      <int>    <int>    <int>
#1 apples         1        1        0
#2 bananas        1        1        1

和一样data.table

library(data.table)
setDT(df)[, lapply(.SD, function(x) +any(x > 0)), by=produce]

推荐阅读