根据数据类型有条件地替换NA

时间:2018-03-29 12:31:50

标签: r types integer na

我有一个包含80多个不同变量的数据库,其中大多数都有NA。一些变量是整数,一些是因子。 我想要做的是开发一个功能: 1.查看我的列表; 2.标识列类型; 3.如果列中包含的数据类型是因子,则函数将NA替换为“其他”; 但是,如果列中包含的数据类型是整数,请替换为数字0。 有任何想法吗?  谢谢,伙计们。

2 个答案:

答案 0 :(得分:1)

FOO <- function(x){
  if(is.numeric(x)){
    x[is.na(x)] <- 0
  }
  if(is.factor(x)){
    x[is.na(x)] <- "Others"
  }
return(x)
}

现在只需使用lapply循环遍历数据的多个列,例如df[1:10] <- lapply(df[1:10], FOO)

注意:这要求因子级别"Others"已存在于您想要更改的每个因子变量中。如果不是这种情况,请使用

FOO <- function(x){
  if(is.numeric(x)){
    x[is.na(x)] <- 0
  }
  if(is.factor(x)){
    x <- as.character(x)
    x[is.na(x)] <- "Others"
    x <- as.factor(x)
  }
  return(x)
}

但这可能会重新安排因子水平的顺序。

答案 1 :(得分:0)

使用dplyrforcats套餐:

library(dplyr)
library(forcats)

# sample data frame
df <- data_frame(fac1 = as.factor(c('NY', NA, 'PA', 'MN', 'OH', 'TX', NA)),
                 int1 = as.integer(c(1,2,3,NA,NA,6,7)),
                 fac2 = as.factor(c('red', 'blue', NA, 'green', 'green', NA, 'yellow')),
                 int2 = as.integer(c(1,NA,3,4,5,NA,7)))

df %>% 
  mutate_if(is.integer, funs(replace(., is.na(.), 0))) %>% 
  mutate_if(is.factor, funs(fct_explicit_na(., na_level = 'Other')))

# A tibble: 7 x 4
    fac1  int1   fac2  int2
  <fctr> <dbl> <fctr> <dbl>
1     NY     1    red     1
2  Other     2   blue     0
3     PA     3  Other     3
4     MN     0  green     4
5     OH     0  green     5
6     TX     6  Other     0
7  Other     7 yellow     7