简体   繁体   English

在R数据框中的选定因子列中将NA更改为“ N”

[英]Changing NA to “N” in selected factor columns in R data frame

I have a the following data frame with factor columns. 我有一个带有因子列的以下数据框。

set.seed(1234)
df <- data.frame(a=sample(c("1","2",NA), 10, replace=T),
                b=sample(c("1","2",NA), 10, replace=T), 
                c=sample(c("1","2","3",NA), 10, replace=T))

which is 这是

df
      a    b    c
1     1 <NA>    2
2     2    2    2
3     2    1    1
4     2 <NA>    1
5  <NA>    1    1
6     2 <NA> <NA>
7     1    1    3
8     1    1 <NA>
9     2    1 <NA>
10    2    1    1

Now, I want to create a new level "N" for selected columns and convert all NA in those column to "N". 现在,我想为所选列创建一个新级别“ N”,并将这些列中的所有NA都转换为“ N”。 I make a vector of selected column names by 我将所选列名的向量

selected <- c("b", "c")

and then try to use apply in the following way 然后尝试通过以下方式使用apply

 apply(df, 2, function(x) {(if x %in% selected) x <- factor(x, levels=c(levels(x), 'N'))})

But it gives error: 但是它给出了错误:

Error: unexpected symbol in "apply(df, 2, function(x) {(if x"

In my original data, I have lots of columns. 在我的原始数据中,我有很多列。 So I want to avoid doing it column by column. 因此,我想避免逐列进行。

The 'levels' of the 'selected' columns before the operation is: 操作前“选定”列的“级别”为:

 lapply(df[selected], levels)
 #$b
 #[1] "1" "2"

 #$c
 #[1] "1" "2" "3"

We can 'loop' over the columns in the 'selected' with lapply , include 'N' as one more level in each column, and replace the 'NA' values with 'N'. 我们可以使用lapply在“ selected”中的列上“循环”,在每列中lapply “ N”个级别,并用“ N” replace “ NA”值。

 df[selected] <- lapply(df[selected], function(x) {
          levels(x) <- c(levels(x), 'N')
           replace(x, which(is.na(x)), 'N')
            })

Or another option is recode from car , where we can directly change 'NA' to 'N'. 另一个选择是从car recode ,我们可以直接将'NA'更改为'N'。 It will automatically update the levels. 它将自动更新级别。

 library(car)
 df[selected] <- lapply(df[selected], recode, "NA='N'")
 lapply(df[selected], levels)
 #$b
 #[1] "1" "2" "N"

 #$c
 #[1] "1" "2" "3" "N"

Another useful function is addNA if we want to add "NA" one of the levels 如果我们要添加“ NA”级别之一,则另一个有用的功能是addNA

df[selected] <- lapply(df[selected], addNA)

NOTE: The output of apply on a non-numeric column will be 'character' class. 注意:在非数字列上apply的输出将是'character'类。 I guess that is not you wanted. 我想那不是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM