r - Drop factor levels containing single observation -
i'd know if there exists simple function (similar drop.levels) drop levels factor containing 1 observation. i'll provide reproducible example below. until i'm able store names of factors containing levels 1 observation, pain write code drop specific levels, there quick way it?
db0 <- data.frame(let = c(sample(letters[1:5], 99, replace = t),"z"), let2 = sample(letters[6:11], 100, replace = t)) #checking factor has levels 1 obs faclevels <- lapply(db0, table) facnames <- list() for(i in 1:length(faclevels)){ facnames[i]<-ifelse(min(faclevels[[i]])==1, names(faclevels[i]), na) } facnames <- as.character(facnames[!is.na(facnames)])
basically want drop z level in let. thanks.
the for
loop here set factor level 1 observation na removes factor level column refactoring it.
db0 <- data.frame(let = c(sample(letters[1:5], 99, replace = t),"z"), let2 = sample(letters[6:11], 100, replace = t)) #checking factor has levels 1 obs faclevels <- lapply(db0, table) # make list each factor level has 1 value to_change <- lapply(faclevels, function(x) names(x)[x==1]) for(i in 1:ncol(db0)){ if(length(to_change[[i]])>0){ # set na db0[which(db0[,i] %in% to_change[[i]]),i] <- na # removes factor level, remove code below if not # wanted db0[,i] <- as.factor(db0[,i]) } } > tail(db0) let let2 95 b 96 g 97 c k 98 d j 99 d f 100 <na> j > levels(db0[,i]) [1] "f" "g" "h" "i" "j" "k"
Comments
Post a Comment