我需要的是一种用新元素替换索引向量中元素的方法。这只是愚蠢的数据:
index <- sample(1:4, 1000, replace = TRUE)
请注意,我正在寻找的东西也应该适用
index <- sample(c("one", "two", "duck", "something"), 1000, replace = TRUE)
我想用以下1:4
内容替换元素:
cols <- c("black", "red", "green", "blue")
我想要的是:
> index
[1] 1 4 3 3 2 4 1 ...
> result
[1] "black" "blue" "green" "green" "red" "blue" "black" ...
我相信我刚才看到了一个函数,但是我不记得它是什么。gsub()
不起作用,因为它只能做一个;replace
也没有,等等。我真的很期待我正在寻找的功能。
我们有一个来自sample
ing的数字索引。因此,只需用[
值向量替换那些索引,其中“ black”将替换1
,“ red” 2
,“ green”,第3个,依此类推...
cols <- c("black", "red", "green", "blue")
index <- sample(1:4, 1000, replace = TRUE)
cols[index]
如果索引是
index <- sample(c("one", "two", "duck", "something"), 1000, replace = TRUE)
将“ cols”更改为命名向量,然后进行替换
setNames(cols, c("one", "two", "duck", "something"))[index]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句