我有文本变量 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))
Run Code Online (Sandbox Code Playgroud)
将其转换为字符,使用简单的子集并将其转换回因子(可选):
mydat$x1 <- as.character(mydat$x1)
mydat$x1[mydat$x1 == 'd'] <- 'f'
# optional
mydat$x1 <- as.factor(mydat$x1)
Run Code Online (Sandbox Code Playgroud)
或者 - 当您正在寻找dplyr解决方案时:
library(dplyr)
mydat %>%
mutate(x1 = as.character(x1),
x1 = if_else(x1 == 'd', 'f', x1),
x1 = as.factor(x1))
Run Code Online (Sandbox Code Playgroud)
两者都会产生
x1 x2 x3
1 a 1 2
2 b 1 2
3 c 1 2
4 f 1 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10747 次 |
| 最近记录: |