简体   繁体   中英

Use a named list as an index to subset a vector of strings

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?

Another similar approach :

R> unlist(M[X])
 a  b  b  a  c 
11 22 22 11 33 

You need to make only a couple of small changes in your code:

  • Use a named vector instead of a named list (this is optional - a named list will also work)
  • But more importantly, use single brackets [ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM