R 基于数据类型的NA条件替换
我有一个包含80多个不同变量的数据库,其中大多数变量都有NAs。有些变量是整数,有些是因子。 我想做的是开发一个函数: 1.查看我的列列表; 2.标识列类型; 3.如果列中包含的数据类型为factor,则函数将NA替换为其他; 4.但是,如果列中包含的数据类型是整数,则替换为数字0。 有什么想法吗? 谢谢,伙计们R 基于数据类型的NA条件替换,r,types,integer,na,R,Types,Integer,Na,我有一个包含80多个不同变量的数据库,其中大多数变量都有NAs。有些变量是整数,有些是因子。 我想做的是开发一个函数: 1.查看我的列列表; 2.标识列类型; 3.如果列中包含的数据类型为factor,则函数将NA替换为其他; 4.但是,如果列中包含的数据类型是整数,则替换为数字0。 有什么想法吗? 谢谢,伙计们 FOO <- function(x){ if(is.numeric(x)){ x[is.na(x)] <- 0 } if(is.factor(x)){
FOO <- function(x){
if(is.numeric(x)){
x[is.na(x)] <- 0
}
if(is.factor(x)){
x[is.na(x)] <- "Others"
}
return(x)
}
不过,这可能会重新排列因子级别的顺序。使用dplyr和forcats包:
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
欢迎来到StackOverflow!请阅读相关信息以及如何给出建议。这将使其他人更容易帮助你。
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