Using a look-up table in R without resorting to SQL

Suppose I have a list of letters, each with an associated value that is either 0, 1, or 2.
l <- list(c("A", "W", "Z", "C", "E", "P")
val - list(c(0, 1, 1, 2, 0, 0)

Now I get a list of letters "xx" that I have to tag with a value, using val as a look-up table to arrive at the vector yy.
So if xx <- list(c("W", "W", "P" "C")
I'd like to get yy <- c(1, 1, 0, 2)

This is a simplistic example. In my work I often have 100's of "words" rather than "letters", each of which is assigned a value. Then when I get some text I have to obtain the value of each word.



All of the square brackets make this look more complicated than it is.

l <- list(c("A", "W", "Z", "C", "E", "P"))
val <- list(c(0, 1, 1, 2, 0, 0))
xx <- list(c("W", "W", "P", "C"))           
names(val[[1]]) <- l[[1]]           
yy <- val[[1]][xx[[1]]]           
#> W W P C 
#> 1 1 0 2

Created on 2020-08-18 by the reprex package (v0.3.0)

good solution, as a special case these lists are not more complex than vectors because they are each of a single type, so

l <- c("A", "W", "Z", "C", "E", "P")
val <- c(0, 1, 1, 2, 0, 0)
xx <- c("W", "W", "P", "C")       
names(val) <- l           
yy <- val[xx]

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.