简体   繁体   English

重命名R中的变量类别

[英]rename the category of variable in R

I have text variable X1 . 我有文字变量X1 It takes value A,B,C,D . 它取值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? 我需要将类别D重命名为F.所以在输出中我期望A,B,C,F我该怎么办? 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))

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: 或者 - 正在寻找一个dplyr解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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