问题描述
我有一个看起来像这样的data.frame(数据在这里:https://github.com/JMcrocs/MEPVote/blob/master/MEP_ID_EPG.rds)
head(MEP_ID_EPG)
mepid EPG
1 197701 GUE.NGL
2 197533 GUE.NGL
3 197521 GUE.NGL
以及2336个列表的大列表(数据:https://github.com/JMcrocs/MEPVote/blob/master/AllVotes.rds)
str(AllVotes,max.level = 7,list.len = 5)
List of 2336
$ :List of 7
..$ Votes :List of 3
.. ..$ +:List of 2
.. .. ..$ total : num 83
.. .. ..$ groups:List of 6
.. .. .. ..$ GUE/NGL :List of 23
.. .. .. .. ..$ : Named num 197701
.. .. .. .. .. ..- attr(*,"names")= chr "mepid"
.. .. .. .. ..$ : Named num 197533
.. .. .. .. .. ..- attr(*,"names")= chr "mepid"
.. ..$ -:List of 2
.. .. ..$ total : num 142
.. .. ..$ groups:List of 8
.. .. .. ..$ ECR :List of 27
.. .. .. .. ..$ : Named num 198096
.. .. .. .. .. ..- attr(*,"names")= chr "mepid"
.. .. .. .. ..$ : Named num 197467
.. ..$ 0:List of 2
.. .. ..$ total : num 72
.. .. ..$ groups:List of 4
.. .. .. ..$ ID :List of 3
.. .. .. .. ..$ : Named num 197480
.. .. .. .. .. ..- attr(*,"names")= chr "mepid"
.. .. .. .. ..$ : Named num 197482
我的目标是,如果他对yea(“ +”),nay(“-”)投票,则在MEP_ID_EPG的MEP(简单)行中添加“ +”,“-”或“ 0”其他(“ 0”)(如果NA或他投票(“ 0”))。 用更复杂的语言,应该看起来像这样
如果( MEP_ID_EPG $ mepid在AllVotes [[x]] $ Votes $'+'
的子列表中然后是MEP_ID_EPG $ [[x]] =='+')
if(MEP_ID_EPG $ mepid在AllVotes [[x]] $ Votes $'-'
的子列表中然后是MEP_ID_EPG $ [[x]] =='-')
else('0')
结果应该是这样
head(MEP_ID_EPG)
mepid EPG 1 2 ... 2336
1 197701 GUE.NGL + + ... +
2 197533 GUE.NGL 0 + ... 0
3 197521 GUE.NGL - 0 ... -
目前我只能这样做
MEP_ID_EPG$mepid %in% AllVotes[[1]]$Votes$'+'$groups$`GUE/NGL`[[1]]
有人可以帮我吗?
提前谢谢!
解决方法
AllVotes是2336个元素的未命名列表,每个元素都是一个特定的投票会话。因此,我们需要使用 Button btn7 = new Button("7");
btn7.setFont(new Font("Arial",Font.BOLD,18));
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = btn7.getText();
txtDisplay.setText(EnterNumber);
}
});
或map()
或lapply()
循环对其元素进行循环。
此外,对于给定的会话for
,可以通过以下方式获得对i
进行投票的MEP的ID:
+
,与unlist(AllVotes[[i]]$votes$`+`$groups)
和-
相同。
由于您希望每次选择的输出都带有一列,因此让我们创建一个空白表并填充它。我将使用一个矩阵,在这里我觉得它更实用。
0
在R中通常不建议for循环,但是在这里它工作得很好,我不确定apply-family函数会带来什么好处。
看看:
meps2 <- matrix(NA_character_,nrow = nrow(meps),ncol=length(AllVotes),dimnames = list(meps$mepid,as.character(1:length(AllVotes))))
for(i in 1:length(AllVotes)){
meps2[as.character(unlist(AllVotes[[i]]$votes$`+`$groups)),i] <- "+"
meps2[as.character(unlist(AllVotes[[i]]$votes$`-`$groups)),i] <- "-"
meps2[as.character(unlist(AllVotes[[i]]$votes$`0`$groups)),i] <- "0"
}
最后,我们只需要组装决赛桌。行顺序相同,因此我们甚至不需要meps2[1:10,1:10]
table(is.na(meps2))
# -> note there still are lots of NA.
# Possibly MEPs that were not present?
或merge
。
match
编辑:使用meps <- cbind(meps,meps2)
的想法可行,但效率不高。您需要在每个投票会议上循环,提取3个投票者列表,然后使用%in%
(每个循环本身)为每个列表上的每个MEP循环。那将是3个循环。在这里,通过扭转问题,我们在表决会议上显式循环,并在每个列表(-,+,0)的MEP上隐式循环。这只有2个循环,并且在矩阵中填充特定行非常有效。看起来像(经过适当的初始化):
%in%