[英]dplyr: mutate() and mutate_if()
I want to change all NAs in columns to 0. I can do it with mutate()
, but not with mutate_if()
. 我想将列中的所有NA更改为0.我可以使用
mutate()
,但不能使用mutate_if()
。
This works: 这有效:
> test <- tibble(Q3.2 = c(1,2, NA, NA, 3),
Q8.2 = c(2, NA, 1, NA, 4))
> test %>% select_("Q3.2", "Q8.2") %>%
mutate(Q3.2 = ifelse(is.na(Q3.2), 0, Q3.2),
Q8.2 = ifelse(is.na(Q8.2), 0, Q8.2))
But this doesn't: 但这不是:
> test %>% select_("Q3.2", "Q8.2") %>%
+ mutate_if(is.na(.), 0, .)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'p' of mode 'function' was not found
That is not what mutate_if
does. 这不是
mutate_if
作用。 It predicates on columns not rows, and therefore does not work the same as the ifelse
within mutate
. 它预测列而不是行,因此与
mutate
的ifelse
。 To replace all NA
s with 0
s in numeric columns, try eg: 要在数字列中将所有
NA
替换为0
s,请尝试以下操作:
test %>% mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))
Or 要么
test %>% mutate_if(is.numeric, coalesce, ... = 0)
OR: 要么:
library(tidyr)
replace_na(list(Q3.2 = 0, Q8.2 = 0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.