我有一个数据框,我只希望保留至少2箱有汽车的组,而保留组至少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) # 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
输出应为:
Group Car
a 1
a 1
a 0
第二个输出:
Group Car
b 0
b 0
b 0
c 1
c 0
c 0
c 0
我有一个非常庞大的数据集。请帮忙。谢谢!
答案 0 :(得分:2)
对于第一种情况:至少有2例带有汽车的小组
library(dplyr)
df %>%
group_by(Group) %>%
filter(sum(Car) > 1)
# Group Car
# <fct> <dbl>
#1 a 1
#2 a 1
#3 a 0
或以基数R ave
subset(df, ave(Car, Group, FUN = sum) > 1)
和data.table
library(data.table)
setDT(df)[, if (sum(.SD) > 1) .SD, by = Group]
第二种情况:至少有2例没有开车的人群
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
,且基数为R ave
subset(df, ave(Car == 0, Group, FUN = sum) > 1)
与data.table
setDT(df)[, if (sum(.SD == 0) > 1) .SD, by = Group]
数据
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)
答案 1 :(得分:0)
我们可以一步一步使用list
来获取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
如果我们需要提取list
元素,请使用[[
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)