我试图使用forcats::fct_recode用NA字符替换R因子变量中的所有"a“。这就是我试过的:
fct <- forcats::as_factor(c("a", "b"))
fct %>% forcats::fct_recode("c" = "a") #works
fct %>% forcats::fct_recode(NA = "a") #error
fct %>% forcats::fct_recode(NA_character_ = "a") #error有办法用fct_recode实现我的目标吗?
发布于 2020-09-08 08:24:35
您需要使用backticks将值转换为NA:
x1 <- fct %>% forcats::fct_recode(`NA` = "a")
x1
#[1] NA b
#Levels: NA b但是,请注意,尽管这个“看起来”像NA,但它不是真正的NA。它是字符串"NA"。
is.na(x1)
#[1] FALSE FALSE
x1 == 'NA'
#[1] TRUE FALSE要使它成为现实,NA将其替换为NULL。
x2 <- fct %>% forcats::fct_recode(NULL = "a")
x2
#[1] <NA> b
#Levels: b
is.na(x2)
#[1] TRUE FALSE发布于 2020-09-08 22:38:44
我们可以使用na_if
library(dplyr)
fct %>%
na_if('a') %>%
droplevels
#[1] <NA> b
#Levels: bhttps://stackoverflow.com/questions/63789876
复制相似问题