Reputation: 8049
I have a long list of strings which need converting to numbers according to a prespecified mapping. I've put this mapping into a named list, and so can get a single 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 is the correct approach here?
Upvotes: 3
Views: 1010
Reputation: 179398
You need to make only a couple of small changes in your code:
[
rather than double [[
. Single brackets matches an vector, while 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
Upvotes: 5