Use a named list as an index for a subset of a vector of strings
I have a long list of strings that need to be converted to numbers according to a given mapping. I put this mapping in a named list and so I can get one element, but I can't figure out how to apply it to a vector
For example:
> X <- c("a", "b", "b", "a", "c")
> M <- list(a = 11, b = 22, c = 33)
> M[["a"]]
[1] 11
> M[[X]]
Error in M[[X]] : recursive indexing failed at level 2
> sapply(X, M)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'M' of mode 'function' was not found
What's the correct approach?
+3
source to share
2 answers
You only need to make a few small changes to your code:
- Use a named vector instead of a named list (this is optional - a named list will work as well)
- But more importantly, use single parentheses
[
, not double[[
. Individual brackets match a vector, and double brackets match a single element.
Like this:
M <- c(a = 11, b = 22, c = 33)
X <- c("a", "b", "b", "a", "c")
unname(M[X])
[1] 11 22 22 11 33
+5
source to share