Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R如何将其中一个级别更改为NA_R_R Factor - Fatal编程技术网

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"))