One of the factor's levels is an empty string; how to replace it with non-missing value?

倖福魔咒の 提交于 2019-12-13 13:17:13

问题


Data frame AEbySOC contains two columns - factor SOC with character levels and integer count Count:

> str(AEbySOC)
'data.frame':   19 obs. of  2 variables:
 $ SOC  : Factor w/ 19 levels "","Blood and lymphatic system disorders",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Count: int  25 50 7 3 1 49 49 2 1 9 ...

One of the levels of SOC is an empty character string:

> l = levels(AEbySOC$SOC)
> l[1]
[1] ""

I want to replace the value of this level by a non-empty string, say, "Not specified". This does not work:

> library(plyr)
> revalue(AEbySOC$SOC, c(""="Not specified"))
Error: attempt to use zero-length variable name

Neither does this:

> AEbySOC$SOC[AEbySOC$SOC==""] = "Not specified"
Warning message:
In `[<-.factor`(`*tmp*`, AEbySOC$SOC == "", value = c(NA, 2L, 3L,  :
  invalid factor level, NA generated

What's the right way to implement this? I appreciate any input/comment.


回答1:


levels(AEbySOC$SOC)[1] <- "Not specified"

Created a toy example:

df<- data.frame(a= c("", "a", "b"))

df
#  a
#1  
#2 a
#3 b

levels(df$a)
#[1] ""  "a" "b"

levels(df$a)[1] <- "Not specified"

levels(df$a)
#[1] "Not specified" "a"             "b" 

EDIT

As per the OP's comments if we need to find it according the value then in such case, we can try

levels(AEbySOC$SOC)[levels(AEbySOC$SOC) == ""] <- "Not specified"



回答2:


Something like that should work:

test <- data.frame(a=c("a", "b", "", "  "))
str(test)

which.one <- which( levels(test$a) == "" )
levels(test$a)[which.one] <- "NA"



回答3:


A little late to the party but here is a tidyverse solution:

library(tidyverse)

df <- data.frame(SOC = c("", "a", "b"))

df <- df %>% 
   mutate(SOC = fct_recode(SOC, "Not specified" = ""))

Which results in:

            SOC
1 Not specified
2             a
3             b


来源:https://stackoverflow.com/questions/39370738/one-of-the-factors-levels-is-an-empty-string-how-to-replace-it-with-non-missin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!