我有兴趣寻找一种最有效的方法来使用索引来替换数据帧中因子的多个级别。.....以下是数据帧的示例,我称其为“ 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"
答案 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)