2

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))
psysky
  • 3,037
  • 5
  • 28
  • 64
  • Possible duplicate of [Replace a value in a data frame based on a conditional (\`if\`) statement](https://stackoverflow.com/questions/5824173/replace-a-value-in-a-data-frame-based-on-a-conditional-if-statement) – Miha Apr 26 '18 at 11:15
  • 1
    Like this: `factor(mydat$x1, labels=c("A","B","C","F"))`? – Vincent Guillemot Apr 26 '18 at 11:16
  • in my case there are 100 000 lables – psysky Apr 26 '18 at 11:17
  • See `dplyr::recode` or the `forcats` package –  Apr 26 '18 at 11:19
  • Possible duplicate of [How to rename a single column in a data.frame?](https://stackoverflow.com/questions/7531868/how-to-rename-a-single-column-in-a-data-frame) – Uri Goren Apr 26 '18 at 12:41

1 Answers1

5

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
Jan
  • 42,290
  • 8
  • 54
  • 79