我在R中有一个名为data.frame
的{{1}},看起来像这样(请参阅生成此数据框的代码的结尾或CSV表here):
possibleVotes
我尝试使用+------+------+------+------+------+-------------+--------+------+
| Var1 | Var2 | Var3 | Var4 | Var5 | nSuccesses1 | p1 | use1 |
+------+------+------+------+------+-------------+--------+------+
| 0 | 0 | 0 | 1 | 0 | 0 | 0.0225 | 0 |
+------+------+------+------+------+-------------+--------+------+
| 1 | 0 | 0 | 1 | 0 | 1 | 0.1275 | 0 |
+------+------+------+------+------+-------------+--------+------+
| 0 | 1 | 0 | 1 | 0 | 1 | 0.1275 | 0 |
+------+------+------+------+------+-------------+--------+------+
| 1 | 1 | 0 | 1 | 0 | 2 | 0.7225 | 1 |
+------+------+------+------+------+-------------+--------+------+
过滤代码,如下所示:
dplyr
我的预期结果只是round <- 1
roundTotal <- 2
pRound1 <- possibleVotes %>%
select_(num_range("Var", 1:2), paste0("nSuccesses", round), paste0("p", round), paste0("use", round)) %>%
distinct_() %>%
filter_(paste0("nSuccesses", round) == roundTotal & paste0("use", round) == 1) %>%
select_(paste0("p", round)) %>%
sum()
为0.7225。不幸的是我收到了这个错误:
错误:列
pRound1
必须是1d原子向量或列表
我经历了每一步并发现:
p1
。distinct_()
步骤。filter_()
无效(未选择num_range()
和Var1
列)我不知道错误意味着什么,也不知道为什么Var2
没有给我预期的结果......
如何解决此问题?谢谢!
编辑:在@Axeman的慷慨帮助下,我尝试了num_range()
:
filter_()
不幸的是它仍然给出了这个:
错误:列
filter_(lazyeval::interp(~a == b, a = as.name(paste0("nSuccesses", round)), b = roundTotal)) %>% filter_(lazyeval::interp(~a == b, a = as.name(paste0("use", round)), b = 1))
必须是1d原子向量或列表
编辑2:我使用R 3.4.0运行dplyr 0.5.0。
编辑3:以下是我用于生成原始p1
数据框的完整代码:
possibleVotes
答案 0 :(得分:2)
一个简单的诀窍是paste0
将所有事物组合在一起创造一个条件,摆脱其他麻烦的条件构建过程。你可以建立一个像这样的条件:paste0("nSuccesses", round, "==", roundTotal, "&", "use", round, "== 1")
它会给你"nSuccesses1==2&use1== 1"
,而filter_
只有dmatrix <- t(matrix(c(0,0,0,1,0,0,0.0225,0,
1,0,0,1,0,1,0.1275,0,
0,1,0,1,0,1,0.1275,0,
1,1,0,1,0,2,0.7225,1), nrow = 8, ncol = 4))
possibleVotes <- data.frame(dmatrix)
colnames(possibleVotes) <- c("Var1","Var2","Var3","Var4","Var5","nSuccesses1","p1","use1")
round <- 1
roundTotal <- 2
pRound1 <- possibleVotes %>%
select_(~num_range("Var", 1:2), paste0("nSuccesses", round), paste0("p", round), paste0("use", round)) %>%
distinct_() %>%
filter_(paste0("nSuccesses", round, "==", roundTotal, "&", "use", round, "== 1")) %>%
select_(paste0("p", round)) %>%
sum()
。
编辑:我的所有代码:
{{1}}