[R] change specific factor level values to NA in data frame

Rui Barradas ruipbarradas at sapo.pt
Mon Sep 30 18:52:10 CEST 2013


Hello,

A possibility is the following.



icol <- sapply(df, is.factor)
df[icol] <- lapply(df[icol], function(x){
	x[as.character(x)  %in% c('Not applicable', 'Invalid', 'Missing')] <- NA
	x})


Hope this helps,

Rui Barradas

Em 30-09-2013 10:42, Daniel Caro escreveu:
> Dear R-users
>
> I am trying to replace specific factor level values in a data frame
> with NAs. The data frame includes different kind of variables (e.g,
> characters, numbers, and factors). I'd like to replace all 'Not
> applicable', 'Invalid', 'and Missing' for NA.
>
> For example:
>
> f.level <- c('Yes', 'No', 'Not applicable', 'Invalid', 'Missing')
> df <- data.frame(x1=runif(100), x2=sample(f.level, 100, replace=T),
> x3=sample(f.level, 100, replace=T))
>
> I try changing the values by
> df[df %in% c('Not applicable', 'Invalid', 'Missing'), ] <- NA
>
> but nothing seems to change
> summary(df)
>
> My data frame has many more factors. Any advice?
>
> Thank you,
> Daniel
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list