R如何将其中一个级别更改为NA
我有一个数据集,其中一列有系数级别R如何将其中一个级别更改为NA,r,r-factor,R,R Factor,我有一个数据集,其中一列有系数级别“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)=='NotPerform
“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
x我修改了我的旧答案,并提供截至2016年9月您可以做的事情。随着dplyr
包的开发,现在您可以使用recode\u 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
x或只需使用内置的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
x通过tidyverse
管道将其中一个级别设置为NA
,%%>
这可能是一个更好的评论,但我没有那么多的声誉。
在我的例子中,income
变量是int
,其值为c(1:7,9)
。在这些级别中,“9”表示“不想回答”
##当所有int都应为fctr时
新数据%mutate\u if(is.integer,as.factor)%>%
变异(收入=fct_重新编码(收入,NULL=“9”))
我还尝试了recode()
,但它不起作用 作为旁注,虽然x[x==“NotPerformed”],但这可以更新为包含forcats
包:fct\u recode(x,NULL=“NotPerformed”)
。
## when all int should be fctr
New_data <- data %>% mutate_if(is.integer, as.factor) %>%
mutate(income = fct_recode(income, NULL = "9"))