0

I have a vector containing numeric elements like below:

jnk1<-c(0,2,1,3,4,2,1,2)

In another character vector I want to assign colors corresponding to each element of numeric vector jnk1.

m<-c("red","green","blue","brown","purple","green","blue","green")

I've written the following code using for loops to automate the process:

m<-as.character()
for (i in 1:length(jnk1)){
for (j in 1:length(jnk1)){
for (k in 1:length(jnk1)){
for (l in 1:length(jnk1)){
for (o in 1:length(jnk1)){
if (jnk1[i]==0){
m[i]<-c("red")}
if (jnk1[j]==1){
m[j]<-c("blue")}
if (jnk1[k]==2){
m[k]<-c("green")}
if (jnk1[l]==3){
m[l]<-c("brown")}
if (jnk1[o]==4){
m[o]<-c("purple")}}}}}}

The above code gets the job done for small number of iterations but for larger iterations it is quite inefficient and time consuming. Is it possible to get the job done using a more efficient code?

Debjyoti
  • 177
  • 1
  • 1
  • 9

1 Answers1

5

A pretty straightforward way to do this would be to use a lookup vector (note that the +1 is necessary since R indices start at 1 and the minimum value in your vector is 0).

lookup <- c('red', 'blue', 'green', 'brown', 'pink')
m <- lookup[jnk1+1]

It's also worth noting that you could use a single for loop, you don't need a separate index in each if condition.

ClancyStats
  • 1,219
  • 6
  • 12