a different ben
a different ben

Reputation: 4008

Replace values of integer vector by matching to position index of values in character vector

I know this is going to be simple, but I haven't been able to work it out or find a solution by searching.

I have a matrix of integers with integer values from 1:n (created by converting some factors to indices). I want to match those values to a vector of n colours, given in hex string values (generated using the scales package).

Y <- sample(1:7, 20, replace=TRUE)  # for example
classcols <- c("#F8766D", "#C49A00", "#53B400", "#00C094", "#00B6EB", "#A58AFF", 
"#FB61D7")
# manually replace:
Y[Y==1] <- classcols[1]

I am a bit slow on the uptake, and can't work out how to do this except manually as above. The reason may show how stupid I am:

plot(X, col=Y)  # X has same shape as Y. I want to control the colours a bit more.

Upvotes: 0

Views: 493

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193657

It sounds as if you're just trying to do this:

classcols[Y]
#  [1] "#C49A00" "#53B400" "#00B6EB" "#FB61D7" "#C49A00" "#FB61D7" "#FB61D7" "#00B6EB"
#  [9] "#00B6EB" "#F8766D" "#C49A00" "#C49A00" "#00B6EB" "#53B400" "#A58AFF" "#00C094"
# [17] "#A58AFF" "#FB61D7" "#53B400" "#A58AFF"

Here, I've just used the values of "Y" to index the values in "classcols". You can, of course, reassign the output to another vector to use as required.

Upvotes: 1

Related Questions