重命名R中的变量类别

时间:2018-04-26 11:09:19

标签: r dataframe dplyr

我有文字变量X1。它取值A,B,C,D。我需要将类别D重命名为F.所以在输出中我希望A,B,C,F 我该怎么做? 这是我的数据集

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))

1 个答案:

答案 0 :(得分:3)

将其转换为字符,使用简单的子集并将其转换回因子(可选):

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

或 - 正如您在寻找dplyr解决方案:

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

两者都会产生

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