2

I have a numeric vector containing elements of different values

m<-c(0,1,3,1,0,4,6,3,7,1)

I want to replace each unique element with a particular character element: 0 with "NA", 1 with "blue", 3 with "green", 4 with "purple", 6 with "pink", 7 with "yellow" and get the output in a different vector

The output should look like this:

>m2
"NA","blue","green","blue","NA","purple","pink","green","yellow","blue"
Debjyoti
  • 177
  • 1
  • 1
  • 9

2 Answers2

3

Here you go...

dplyr::recode(m, "1" = "blue", "3" = "green", "4" = "purple", "6"="pink", "7"="yellow",.default = "NA")
nikn8
  • 1,016
  • 8
  • 23
2

In base R you can use

m2 <- factor(m, labels = c("NA", "blue", "green", "purple", "pink", "yellow"))

Output

# [1] NA     blue   green  blue   NA     purple pink   green  yellow blue  
# Levels: NA blue green purple pink yellow
Ric S
  • 9,073
  • 3
  • 25
  • 51