gpt4 book ai didi

重命名R中变量的类别

转载 作者:行者123 更新时间:2023-12-05 01:15:50 29 4
gpt4 key购买 nike

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

最佳答案

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

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

关于重命名R中变量的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50041457/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com