Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove 'empty cells' as factor level

Tags:

r

I have a data frame which has one column and column has some data and some empty cells. When I am checking the levels of that column it is showing three levels as it is taking empty cells as one level. I want to delete that level. suppose I have

## editor note: starting from R 4.0.0, `stringsAsFactors` defaults to FALSE
## we now explicitly need `stringsAsFactors = TRUE`
df <- data.frame(fan = c("a","b"," ","a","b"), stringsAsFactors = TRUE) 

I have tried this code

droplevels(df)

but it is not working.

like image 927
Sameer Avatar asked Dec 11 '22 03:12

Sameer


1 Answers

'droplevels' does work. No need for complex code:

df <- data.frame(fan = c("a","b"," ","a","b")) 
df
#  fan
#1   a
#2   b
#3    
#4   a
#5   b

df$fan[df$fan==' ']=NA
df$fan = droplevels(df$fan)
str(df)
#'data.frame':   5 obs. of  1 variable:
# $ fan: Factor w/ 2 levels "a","b": 1 2 NA 1 2
like image 109
rnso Avatar answered Feb 15 '23 12:02

rnso