如何替换向量中多个值的多次出现

时间:2019-03-24 10:29:33

标签: r vector

我在data.frame中有一列,该列的每个唯一值都多次出现,因此需要用不同的值替换。我该如何实现?

我创建了唯一值的因子,并尝试使用gsub函数遍历因子水平来替换每个元素

nf <- factor(1, 2, 3, 4, 5, 6)
let <- c("a", "b", "c", "d", "e", "f")

dat <- c(1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6)

dat <- for (i in levels(nf)){
gsub(i,let[i], dat
}

我希望输出为:

"a" "b" "b" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e" "e" "f" "f" "f" "f" "f" "f" 

但是我却得到了:NULL

1 个答案:

答案 0 :(得分:2)

你紧随其后

let[dat]
#[1] "a" "b" "b" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e" "e" "f" "f" "f" "f"
#[20] "f" "f"

或者,如果您更喜欢factor

factor(dat, labels = let)