0

这个答案可能很明显(我希望如此),但我一直只找到复杂的解决方案。我想做的是根据另一个因素的水平有条件地重新评估一个因素。

这是使用 mtcars 数据集的示例:

data(mtcars)
mtcars$gear <- as.factor(mtcars$gear)
mtcars$am <- as.factor(mtcars$am)

table(mtcars$gear, mtcars$am) # examining the levels
levels(mtcars$gear)
# [1] "3" "4" "5"
levels(mtcars$am)
"0" "1"

现在在那些齿轮级别为“5”的汽车中,我如何将新的“齿轮”级别“6”分配给那些“am”级别为“1”的汽车,同时保留因子级别“3”, 4","5" 代表“齿轮”?这是一个更简单的示例,但考虑到我的数据集的复杂性,我更愿意将向量保留为因子(例如,而不是转换为数字并返回)。

4

1 回答 1

2

齿轮一开始就没有“6”级,所以你需要创建一个:

levels(mtcars$gear) <- c(levels(mtcars$gear), "6")

然后,您可以有条件地分配[<-函数:

mtcars$gear[ mtcars$am==1 ] <- "6"
table(mtcars$gear, mtcars$am)

     0  1
  3 15  0
  4  4  0
  5  0  0
  6  0 13

如果因子属性中没有相应的“级别”,则无法将值分配给因子变量。

于 2014-05-09T23:55:45.687 回答