0

I like to give all values which are in the dat vector a corresponding value which I define in another vector (new_value). I already managed to do somehow, but I like to have a solution without loop:

dat <- c("a","c","b","a","a","c","a","b","b","a")  
old_value <- names(table(dat))
new_value <- 1:length(old_value)
new_dat <- rep(NA, length(dat))

for(z in 1:length(old_value)){
  new_dat[dat==old_value[z]] <- c(1:length(new_value))[z]
}
new_dat

I don't want to use additional libraries. Please only base solutions.

Sotos
  • 51,121
  • 6
  • 32
  • 66
and-bri
  • 1,563
  • 2
  • 19
  • 34

1 Answers1

3

We can use match

new_dat <- new_value[match(dat, old_value)]

For the current example, even

match(dat, old_value)

should work

akrun
  • 874,273
  • 37
  • 540
  • 662