请考虑以下代码:
library(dplyr)
x <- case_when(
FALSE ~ list('a' = 'b'),
TRUE ~ list('c' = 'd')
)
Run Code Online (Sandbox Code Playgroud)
x是
1 $ NA 列表:chr "d"
我希望 x 中的元素 d 具有名称“c”而不是 NA。我错过了什么吗?这是一个错误吗?我怎样才能实现我的预期行为?
准确地说,我希望上面的语句与
x <- list('c' = 'd')
Run Code Online (Sandbox Code Playgroud)
在没有示例数据的情况下,通过简短的代码片段并不清楚您的预期行为是什么。
然而在我看来你的语法错误case_when。
该函数的工作原理如下:
case_when( Condition 1 ~ Value to be assigned if true,
Condition 2 ~ Value to be assigned if true
Run Code Online (Sandbox Code Playgroud)
您使用的条件是FALSE和TRUE,这实际上没有意义,因为会发生以下情况:
x <- case_when(
FALSE ~ list('a' = 'b'), # FALSE is logically never True, so the value is never put in
TRUE ~ list('c' = 'd') # TRUE is always true, x will always be assigned the list
)
Run Code Online (Sandbox Code Playgroud)
所以首先你必须重写你的条件才能有意义。其次,您将列表分配为返回值,我认为这是不正确的。
我假设你想这样做:
x <- case_when(
VAR == 'a' ~ 'b', # If the variable to be evaluated has the value 'a' x will be 'b'
VAR == 'c' ~ 'd') # If the variable to be evaluated has the value 'c' x will be 'd'
)
Run Code Online (Sandbox Code Playgroud)
因此,现在评估现有变量“VAR”并返回由代码确定的 x。请注意,该语句是不完整的,因为NA对于两个条件都不满足的每种情况,它都会自然返回(因此 VAR 既不是“a”也不是“c”)。
所以通常我们这样完成:
x <- case_when(
VAR == 'a' ~ 'b', # If the variable to be evaluated has the value 'a' x will be 'b'
VAR == 'c' ~ 'd') # If the variable to be evaluated has the value 'c' x will be 'd'
TRUE ~ 'Rest Value' # Assigns Rest value to x for all case that do not meet case 1 or 2
)
Run Code Online (Sandbox Code Playgroud)
这似乎是一个已知问题,请参阅此处:
https://github.com/tidyverse/dplyr/issues/4194
Hadley 给出了以下解决方案作为替代方案:
broken_function <- function(value) {
if (value) {
list(a = 1, b = 2)
} else {
lst(a = 2, b = 3)
}
}
Run Code Online (Sandbox Code Playgroud)