简体   繁体   中英

Conditionally Revalue a Factor in R

This answer may very well be obvious (I hope it is), but I kept only finding convoluted solutions. What I'd like to do is conditionally revalue a factor based on the levels of another factor.

Here's an example using the mtcars dataset:

data(mtcars)
mtcars$gear <- as.factor(mtcars$gear)
mtcars$am <- as.factor(mtcars$am)

table(mtcars$gear, mtcars$am) # examining the levels
levels(mtcars$gear)
# [1] "3" "4" "5"
levels(mtcars$am)
"0" "1"

Now among those cars with a gear level of "5", how can I assign a new "gear" level of "6" to those with an "am" level of "1", while retaining the factor levels "3","4","5" for "gear"? This is a much simpler example, but given the complexity of my dataset I'd prefer to keep the vectors as factors (and not transform to numeric and back, for example).

There is no "6" level in gears to begin with, so you need to create one:

levels(mtcars$gear) <- c(levels(mtcars$gear), "6")

You can then conditionally assign with the [<- function:

mtcars$gear[ mtcars$am==1 ] <- "6"
table(mtcars$gear, mtcars$am)

     0  1
  3 15  0
  4  4  0
  5  0  0
  6  0 13

You cannot assign values to a factor variable if there is no corresponding 'level' in the factor attributes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM