r - 多条件下的数据框子集
问题描述
我有一个数据框,其中包含有关巴西地方选举的前两名候选人的信息,如下所示:
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
问候,
解决方案
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
推荐阅读
- db2 - 使用函数拆分 db2 表中的数据
- encryption - 从 multipart/form-data 恢复信息
- c# - Pomelo.EntityFrameworkCore.MySQL DBContext 抛出“Unqualified data type char”异常
- arrays - How to generate a Bitsequence with certain properties
- python - 将 2 个数组组合成一个字典
- excel - 运行时错误“438”对象不支持此属性或方法(发送自动电子邮件)
- xamarin - 检测 Xamarin 表单中 NavigationPage 的后退箭头按下
- xml - 如何获取使用 QXmlSchema 验证的纯文本消息?
- azure - Azure 持续部署忽略图像文件
- extjs - 带有 autoScroll 的容器中的 extjs autoHeight 不起作用