r - 如何折叠具有相同标识符的行并保留非空列值?
问题描述
我有一个表(经过一些初始处理)有多行具有相同的主标识符但具有不同的列值(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中是否有我缺少的简单功能或管道可以处理这个问题?
解决方案
使用基础 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]
推荐阅读
- cakephp - 如果在 cakephp 4 中对随机查找查询使用分页会得到意想不到的结果?
- c - __latent_entropy 在 C 中的用途是什么
- shell - 在Jenkins中编写脚本时用连字符替换下划线
- python - 请求返回 URL https://www.instagram.com/google 的状态码 429
- assembly - 如何将 2 个用户输入与两个数字相乘,然后将它们添加到程序集 8086 处理器中?
- ionic-framework - Ionic - 使用两种方式绑定来更改样式的问题。例如,我使用背景色
- r - 在 R 中自动化投资组合波动率计算
- c# - 使用自动映射器映射对象列表
- python-3.x - 字符串到 Dask 数据框
- node.js - 使用带有 Passport 的 Express 后端将 React 页面重定向到 SAML 登录