使用索引替换几个级别的因子

时间:2018-11-27 14:27:07

标签: r

我有兴趣寻找一种最有效的方法来使用索引来替换数据帧中因子的多个级别。.....以下是数据帧的示例,我称其为“ ph2”,索引为“索引”,而我的方法效率不高,尤其是当我们有大量替代方法时。

index <- data.frame(
   AA = LETTERS[seq( from = 1, to = 5 )],
   BB = c("x1","x2","x3","x4","x5")
    )


ph2 <- data.frame(
    name = LETTERS[seq( from = 1, to = 5 )],
    RE = seq(1:5))


levels(ph2$name)[levels(ph2$name)=="A"] <- "X1"
levels(ph2$name)[levels(ph2$name)=="B"] <- "X2"
levels(ph2$name)[levels(ph2$name)=="C"] <- "X3"
levels(ph2$name)[levels(ph2$name)=="D"] <- "X4"
levels(ph2$name)[levels(ph2$name)=="E"] <- "X5"

1 个答案:

答案 0 :(得分:1)

您可以这样做:

levels(ph2$name) <- paste0("X",ph2$RE[match(levels(ph2$name),ph2$name)])
levels(ph2$name)
#[1] "X1" "X2" "X3" "X4" "X5"

或者如果它们已经按照此处的顺序进行了排序:

levels(ph2$name) <- paste0("X",ph2$RE)