dplyr group_by和任何给出意外输出的命令

时间:2015-06-30 17:50:13

标签: r dplyr

以下是一个示例数据集:

> temp
     ID Visit Issue SpecialExclusion
1  X123     5 12345            FALSE
2  X123     5 67890            FALSE
3  X123     5 34934            FALSE
31 X123     6 34934            FALSE
4  X123     6 67890            FALSE


primaryIssue <- c("12345")
excludedIssue <- c("12345", "67890")

我想要的是仅在主要问题出现时才排除被排除的问题。

> temp %>% group_by(Visit)  %>%  mutate(SpecialExclusion = ifelse(any(Issue ==primaryIssue), Issue %in% excludedIssues, SpecialExclusion))
Source: local data frame [5 x 4]
Groups: Visit

    ID Visit Issue SpecialExclusion
1 X123     5 12345             TRUE
2 X123     5 67890             TRUE
3 X123     5 34934             TRUE
4 X123     6 34934            FALSE
5 X123     6 67890            FALSE

然而,这确实有效:

> temp %>% group_by(Visit) %>% mutate(SpecialExclusion = if(any(Issue == primaryIssue)){Issue %in% excludedIssue}else{SpecialExclusion})
Source: local data frame [5 x 4]
Groups: Visit

    ID Visit Issue SpecialExclusion
1 X123     5 12345             TRUE
2 X123     5 67890             TRUE
3 X123     5 34934            FALSE
4 X123     6 34934            FALSE
5 X123     6 67890            FALSE

那么为什么ifelse失败但是'if-then`有效?谢谢!

1 个答案:

答案 0 :(得分:2)

我认为这是你正在寻找的东西:

temp %>%
  group_by(Visit) %>%
  mutate(SpecialExclusion = any(Issue %in% primaryIssue) & Issue %in% excludedIssue)
# Source: local data frame [5 x 4]
# Groups: Visit
# 
#     ID Visit Issue SpecialExclusion
# 1 X123     5 12345             TRUE
# 2 X123     5 67890             TRUE
# 3 X123     5 34934            FALSE
# 4 X123     6 34934            FALSE
# 5 X123     6 67890            FALSE

您询问ifelse发生了什么。看看这个例子:

ifelse(1 == 1, 2:3, 4:5)
[1] 2
if(1 == 1) 2:3 else 4:5
[1] 2 3

在这个简单的例子中,我测试1是否等于1.如果为TRUE,则返回数字2和3. ifelse似乎不想返回多个值。它只取第一个值2,并将其作为输出。这就是你的功能正在做的事情。那么每个人都不会一直使用if因为它更灵活吗?看看这个例子:

ifelse(1:5 == 1, 'a', 'b')
[1] "a" "b" "b" "b" "b"

我们测试了序列1到5是否等于1.第一个实例应为TRUE,其余应为FALSE。 ifelse执行我们期望的方式。但if只期待测试的一个值。

if(1:5 == 1) 'a' else 'b'
[1] "a"
Warning message:
In if (1:5 == 1) "a" else "b" :
  the condition has length > 1 and only the first element will be used

它给了我们一个警告和一个'a'因为这是测试的第一个结果。 if语句需要一个条件测试,我们给它五个不同的TRUE和FALSE&#39>。

所以ifelse对于产生一个输出的许多测试都是好的。并且if适用于产生许多输出的一个测试。

相关问题