我想删除所选列中具有单个值对的组合。
示例数据:
df <- data.frame(a=c(sample(LETTERS[1:2],99,replace = TRUE),LETTERS[6]),
b=sample(letters[1:10],100,replace=TRUE))
计算不同组合的数量:
df %>% group_by(a, b) %>% summarise(count=n()) %>% data.frame()
# a b count
# 1 A a 9
# 2 A b 4
# 3 A c 4
# 4 A d 2
# 5 A e 4
# 6 A f 2
# 7 A g 12
# 8 A h 6
# 9 A i 6
# 10 A j 7
# 11 B a 3
# 12 B b 5
# 13 B c 5
# 14 B d 5
# 15 B e 3
# 16 B f 8
# 17 B g 3
# 18 B h 6
# 19 B i 1
# 20 B j 4
# 21 F g 1
我可以使用%>% filter(n() > 1)
# a b count
# 19 B i 1
# 21 F g 1
但是,我想只删除以下对而不管它们的频率,即1或大于1.不删除B-i
对的原因是B仍然有其他组合对(a,b) ,c,d,e,f,g,h)。
# a b count
# 21 F g 1
预期产出:
# a b count
# 1 A a 9
# 2 A b 4
# 3 A c 4
# 4 A d 2
# 5 A e 4
# 6 A f 2
# 7 A g 12
# 8 A h 6
# 9 A i 6
# 10 A j 7
# 11 B a 3
# 12 B b 5
# 13 B c 5
# 14 B d 5
# 15 B e 3
# 16 B f 8
# 17 B g 3
# 18 B h 6
# 19 B i 1
# 20 B j 4
即删除组合F-g
,该组合a
只有一个值组合。
情景2:
df2 <- data.frame(c=c(1,2,4,6,8,3), d=c(2,3,5,7,9,5),
e=c('a1','a2','a3','a4','a5','a5'),
a=c('F','F','F','F','F','F'),
b=c('a','b','a','b','a','a'))
# c d e a b
# 1 1 2 a1 F a
# 2 2 3 a2 F b
# 3 4 5 a3 F a
# 4 6 7 a4 F b
# 5 8 9 a5 F a
# 6 3 5 a5 F a
df2 %>% group_by(a, b) %>% filter(n()>2)
# Source: local data frame [4 x 5]
# Groups: a, b [1]
#
# # A tibble: 4 x 5
# c d e a b
# <dbl> <dbl> <fctr> <fctr> <fctr>
# 1 1 2 a1 F a
# 2 4 5 a3 F a
# 3 8 9 a5 F a
# 4 3 5 a5 F a
df2 %>% group_by(a, b) %>% filter(n()>2) %>% summarise(count=n())
# Source: local data frame [1 x 3]
# Groups: a [?]
#
# # A tibble: 1 x 3
# a b count
# <fctr> <fctr> <int>
# F a 4
答案 0 :(得分:1)
我们收到count
后,按照&#39; a&#39;进行分组。和filter
行数大于1的行
df %>%
count(a, b) %>%
group_by(a) %>%
filter(n()>1)
注意:count
可以替换group_by/summarise
步骤
在大数据集上,最好先执行filter
,然后执行count
df %>%
group_by(a) %>%
filter(n() >1) %>%
count(a, b)