mtcars1 <- mtcars %>%
mutate(blah = LETTERS[seq(1,26, length.out = nrow(.))],
blah2 = letters[seq(1,26, length.out = nrow(.))])
# sprinkle some random NA values
mtcars1$blah[c(1,3,5,10,11)] <- NA
mtcars1$blah2[c(1,2,5,15,20)] <- NA
mtcars1 %>%
mutate_at(blah:blah2, function(x) {
if_else(is.na(x), 0, x)
})
返回:
Error in check_dot_cols(.vars, .cols) : object 'blah' not found
如何使用 dplyr/tidyverse 方法在多个列中将 NA 替换为 0?
最佳答案
我们可以将列名的 ranger 包装在 vars
中,并确保返回 type
与 if_else
相同(或者case_when
)基于?if_else
Compared to the base ifelse(), this function is more strict. It checks that true and false are the same type. This strictness makes the output type more predictable, and makes it somewhat faster.
library(dplyr)
mtcars1 %>%
mutate_at(vars(blah:blah2), ~ if_else(is.na(.), '0', .))
这里,使用带有 ~
的 tidyverse 简洁选项,而不是匿名函数调用 (function(x)
),并且 'blah'、'blah2' 分别是character
类型,true
的返回类型也带引号 ('0'
)
专门用于替换 NA
的另一个选项是 tidyr
中的 replace_na
,而不是 if_else
library(tidyr)
mtcars1 %>%
mutate_at(vars(blah:blah2), replace_na, '0')
关于r - mutate_at 将 NA 替换为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563691/