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

dplyr group_by and any command giving unexpected output

这是一个示例数据集:

> 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”有效?谢谢!

我想这就是您要找的:

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。如果为真,return 数字 2 和 3。ifelse 似乎不想 return 不止一个值。它只取第一个值 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。

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