Replacing index vector with levels

We have a numeric index from sampleing. So just use [ to replace those index with a vector of values where “black” will replace the 1, “red”, the 2, “green”, the 3rd, and so on…

cols <- c("black", "red", "green", "blue")
index <- sample(1:4, 1000, replace = TRUE)
cols[index]

If the index is

index <- sample(c("one", "two", "duck", "something"), 1000, replace = TRUE)

change the ‘cols’ to a named vector and then do the replacement

setNames(cols, c("one", "two", "duck", "something"))[index]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top