How to replace <NA> with a number for a single factor variable in R? -
- data: dat
- variable: v1
i have tried this, did not replace "< na >" (no spaces)
cwm$v1 <- factor(cwm$v2) replace(cwm$v1, cwm$v1=="< na >", 9)
again no spaces. gives me variable still "< na >"
the symbol <na>
missing value in factor:
> factor(c("a",na,"b")) [1] <na> b levels: b
hence can use is.na
missing values, see this:
> v1 <- factor(c("a", na,"b")) > v1[is.na(v1)] <- 9 > v1 [1] <na> b levels: b warning message: in `[<-.factor`(`*tmp*`, is.na(v1), value = 9) : invalid factor level, na generated
the reason simple: 9 not level of factor. in order done, need replacement before convert factor:
> v2 <- c("a",na,"b") > v2[is.na(v2)] <- 9 > v1 <- factor(v2) > v1 [1] 9 b levels: 9 b
now have 9 separate level. if don't want this, shouldn't use factor in first place. in case start factor, convert character
first:
> v1 <- factor(c("a", na,"b")) > v1 <- as.character(v1) > v1[is.na(v1)] <- 9 > v1 [1] "a" "9" "b"
Comments
Post a Comment