I have a dataframe and I want to only keep the groups that have at least 2 cases with cars AND another output to keep groups will at least 2 cases of No car:
Group = c('a','a','a','b','b','b','c','c','c','c')
Car = c(1,1,0,0,0,0,1,0,0,0) # 1 = Have car, 0 = No car
df = data.frame(Group,Car)
df$Group = factor(df$Group)
df$Car = factor(df$Car)
Group Car
1 a 1
2 a 1
3 a 0
4 b 0
5 b 0
6 b 0
7 c 1
8 c 0
9 c 0
10 c 0
Output should be:
Group Car
a 1
a 1
a 0
2nd output:
Group Car
b 0
b 0
b 0
c 1
c 0
c 0
c 0
I have a very huge dataset. Please help. Thanks!
For 1st case : groups that have at least 2 cases with cars
library(dplyr)
df %>%
group_by(Group) %>%
filter(sum(Car) > 1)
# Group Car
# <fct> <dbl>
#1 a 1
#2 a 1
#3 a 0
Or base R ave
subset(df, ave(Car, Group, FUN = sum) > 1)
and with data.table
library(data.table)
setDT(df)[, if (sum(.SD) > 1) .SD, by = Group]
For 2nd case : groups with at least 2 cases of No car
df %>%
group_by(Group) %>%
filter(sum(Car == 0) > 1)
# Group Car
# <fct> <dbl>
#1 b 0
#2 b 0
#3 b 0
#4 c 1
#5 c 0
#6 c 0
#7 c 0
and with base R ave
subset(df, ave(Car == 0, Group, FUN = sum) > 1)
with data.table
setDT(df)[, if (sum(.SD == 0) > 1) .SD, by = Group]
data
Group = c('a','a','a','b','b','b','c','c','c','c')
Car = c(1,1,0,0,0,0,1,0,0,0)
df = data.frame(Group,Car)
We can get both the datasets in a list
with one step using split
lst1 <- split(df, df$Group %in% names(which(rowsum(df$Car, df$Group)[,1] >= 2)))
lst1
#$`FALSE`
# Group Car
#4 b 0
#5 b 0
#6 b 0
#7 c 1
#8 c 0
#9 c 0
#10 c 0
#$`TRUE`
# Group Car
#1 a 1
#2 a 1
#3 a 0
If we need to extract the list
elements, use [[
lst1[[1]]
lst1[[2]]
Group <- c('a','a','a','b','b','b','c','c','c','c')
Car <- c(1,1,0,0,0,0,1,0,0,0)
df <- data.frame(Group,Car)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.