[英]Losing names when using lists as results of dplyr::case_when
請考慮以下代碼:
library(dplyr)
x <- case_when(
FALSE ~ list('a' = 'b'),
TRUE ~ list('c' = 'd')
)
x是
1 $ NA列表:chr“ d”
我希望x中的元素d具有名稱“ c”,而不是NA。 我想念什么嗎? 這是錯誤嗎? 我如何實現預期的行為?
確切地說,我希望上述陳述的結果與
x <- list('c' = 'd')
尚不清楚從短代碼段開始並且沒有示例數據的預期行為是什么。
但是在我看來, case_when
語法錯誤。
該函數的工作方式如下:
case_when( Condition 1 ~ Value to be assigned if true,
Condition 2 ~ Value to be assigned if true
您使用的條件是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
)
因此,首先您必須重寫條件才有意義。 其次,您將列表分配為返回值,我認為這是不正確的。
我假設您想這樣做:
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'
)
因此,這現在將評估現有變量“ 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
)
看來這是一個已知問題,請參見此處:
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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.