psysky
psysky

Reputation: 3195

rename the category of variable in R

I have text variable X1. It takes value A,B,C,D. I need to rename category D to F. So in output i expect A,B,C,F How can i do it? here my dataset

mydat=structure(list(x1 = structure(1:4, .Label = c("a", "b", "c", 
"d"), class = "factor"), x2 = c(1L, 1L, 1L, 1L), x3 = c(2L, 2L, 
2L, 2L)), .Names = c("x1", "x2", "x3"), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 2

Views: 20087

Answers (2)

derelict
derelict

Reputation: 3906

If the category is a factor variable, you can simply rename using recode with mutate from dplyr.

For example:

mydat %>%
  mutate(x1 = recode(x1, d=f))

Upvotes: 0

Jan
Jan

Reputation: 43169

Convert it to characters, use simple subsetting and convert it back to a factor (optional):

mydat$x1 <- as.character(mydat$x1)
mydat$x1[mydat$x1 == 'd'] <- 'f'
# optional
mydat$x1 <- as.factor(mydat$x1)

Or - as you were looking for a dplyr solution:

library(dplyr)
mydat %>%
  mutate(x1 = as.character(x1),
         x1 = if_else(x1 == 'd', 'f', x1),
         x1 = as.factor(x1))

Both will yield

  x1 x2 x3
1  a  1  2
2  b  1  2
3  c  1  2
4  f  1  2

Upvotes: 6

Related Questions