Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重命名R中变量的类别_R_Dataframe_Dplyr - Fatal编程技术网

重命名R中变量的类别

重命名R中变量的类别,r,dataframe,dplyr,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 = "

我有一个文本变量
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))

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

两者都会让步

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

可能重复如下:
因子(mydat$x1,标签=c(“A”、“B”、“c”、“F”))
?在我的例子中,有100000个标签see
dplyr::recode
for cats
包可能重复
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