首页 > 解决方案 > 多条件下的数据框子集

问题描述

我有一个数据框,其中包含有关巴西地方选举的前两名候选人的信息,如下所示:

Name <- c('Andressa', 'Marcos', 'Anderson', 'Cibelle', 'Ivy', 'Eliana')
Municipality <- c('A', 'A', 'B', 'B', 'C', 'C')
Gender <- c('F', 'M', 'M', 'F', 'F', 'F')
Vote_Share <- c(51, 49, 55, 45, 70, 30)
data <- data.frame(Name, Municipality, Gender, Vote_Share)

Name       Municipality   Gender   Vote_Share 
Andressa         A           F         51
Marcos           A           M         49
Anderson         B           M         55
Cibelle          B           F         45
Ivy              C           F         70
Eliana           C           F         30

我只想在我的数据中保留有关种族是一男一女的城市的信息。

所以,我正在寻找这样的输出:

Name       Municipality   Gender   Vote_Share 
Andressa         A           F         51
Marcos           A           M         49
Anderson         B           M         55
Cibelle          B           F         45

此外,我想在每个自治市的选举中创建另一个包含女性获胜优势(女性投票份额 - 男性投票份额)的对象:

Municipality     Win Margin
A                    2
B                    10

问候,

标签: rdataframedplyr

解决方案


Another way with ave and subset in base R

temp <- subset(data, as.logical(ave(Gender, Municipality, FUN = function(x) 
                all(c('F', 'M') %in% x))))

#      Name Municipality Gender Vote_Share
#1 Andressa            A      F         51
#2   Marcos            A      M         49
#3 Anderson            B      M         55
#4  Cibelle            B      F         45

and then use aggregate to calculate the difference in vote.

aggregate(Vote_Share~Municipality, temp, function(x) diff(range(x)))

#  Municipality Vote_Share
#1            A          2
#2            B         10

推荐阅读