Closed duttashi closed 5 years ago
Solution
Using base R aggregate
we can do
aggregate(.~produce, df, function(x) +any(x > 0))
# produce grocery1 grocery2 grocery3
#1 apples 1 1 0
#2 bananas 1 1 1
Or using 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
and same with data.table
library(data.table)
setDT(df)[, lapply(.SD, function(x) +any(x > 0)), by=produce]
This question was originally asked on SO
Question
How to collapse (or merge?) rows with the same identifier and retain the non-empty (here, any nonzero values) values in each column?
Data
Desired output