我有一个数据集,其中一列有因子水平为"a" "b" "c" "NotPerformed"
。我该如何将所有的"NotPerformed"
因子更改为NA?
将级别设置为NA:
x <- factor(c("a", "b", "c", "NotPerformed"))
x
## [1] a b c NotPerformed
## Levels: a b c NotPerformed
levels(x)[levels(x)=='NotPerformed'] <- NA
x
## [1] a b c <NA>
## Levels: a b c
请注意,因子水平已被移除。
我修改了我的旧回答并提供了截至2016年9月可执行的内容。随着dplyr
包的发展,现在你可以使用recode_factor()
来完成这项工作。
x <- factor(c("a", "b", "c", "NotPerformed"))
# [1] a b c NotPerformed
# Levels: a b c NotPerformed
library(dplyr)
recode_factor(x, NotPerformed = NA_character_)
# [1] a b c <NA>
# Levels: a b c
forcats
еҢ…иҝӣиЎҢжӣҙж–°: fct_recode(x, NULL = "NotPerformed")
гҖӮиҜҘеҮҪж•°зҡ„дҪңз”ЁжҳҜйҮҚж–°зј–з Ғеӣ еӯҗеҸҳйҮҸдёӯзҡ„ж°ҙе№іпјҢе°ҶNULL
еҖјжӣҝжҚўдёәеӯ—з¬ҰдёІ"NotPerformed"гҖӮ - Phil或者直接使用内置的exclude
选项,无论初始变量是字符型还是因子型都可以使用。
x <- c("a", "b", "c", "NotPerformed")
factor(x, exclude = "NotPerformed")
[1] a b c <NA>
Levels: a b c
factor(factor(x), exclude = "NotPerformed")
[1] a b c <NA>
Levels: a b c
tidyverse
的Pipeline,%>%
将其中一个级别设置为NA
。income
变量是int
类型,其值为c(1:7, 9)
。 在这些级别中,“9”代表“不愿意回答”。## when all int should be fctr
New_data <- data %>% mutate_if(is.integer, as.factor) %>%
mutate(income = fct_recode(income, NULL = "9"))
recode()
,但它并没有起作用。
x[x=="NotPerformed"] <- NA
会将值替换为NA
,但它不会删除'NotPerformed'
因子水平。这就是为什么这种方法更可取的原因。 - thelatemail