重命名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个标签seedplyr::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