Home > Blockchain >  how to change a vector to corresponding names without using for loop
how to change a vector to corresponding names without using for loop

Time:09-30

I have a vector c(1,3,4,2,5,4,3,1,6,3,1,4,2), and I want make 1="a", 2="b", and so on

So my final outputs should look like c(a,c,d,b...)

I know that I can use for loop and if statement to do this, but is there any other quicker ways to do?

CodePudding user response:

You may use the built-in constant letters.

vec <- c(1,3,4,2,5,4,3,1,6,3,1,4,2)
res <- letters[vec]
res
#[1] "a" "c" "d" "b" "e" "d" "c" "a" "f" "c" "a" "d" "b"

To replace with any other values you can construct a vector to subset.

value <- c('apples', 'banana', 'grapes', .....)
res <- value[vec]
  • Related