Dan_yef Dan_yef - 4 months ago 24
R Question

How to remove one specific factor level in all factor variables in r?

For example, I have data frame with 6 columns(all are factors).
I want to delete specefic level, for example "no", from all factors, in which this level appears.

I want to drop the factor level "no" from my factor variable and at the same time I want to delete(set to NA's) all answers, that have "no" value.

I have tried this code:

sapply(fact,function(x) levels(x)[levels(x) == "no"] <- NULL)

But this code doesn't work.

How can I do this?

lmo lmo

I think this should accomplish what you are trying to do.

dfNew <- data.frame(lapply(df, function(x) {is.na(x[x=="no"]) <- TRUE; droplevels(x)}))


df <- data.frame(q1=sample(c("yes", "no", "maybe"), 20, replace=TRUE),
                 q2=sample(c("yes", "no", "maybe"), 20, replace=TRUE),
                 q3=sample(c("yes", "no", "maybe"), 20, replace=TRUE))