gpt4 book ai didi

r - 如何折叠具有相同标识符的行并保留非空列值?

转载 作者:行者123 更新时间:2023-12-03 01:26:45 25 4
gpt4 key购买 nike

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

示例表主要标识符“product”

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 中是否有一个我缺少的简单函数或管道可以处理这个问题?

最佳答案

使用基础 R 聚合我们可以做到

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]

关于r - 如何折叠具有相同标识符的行并保留非空列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014241/

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