Home > Software engineering >  How to substitute elements of a list based on identities
How to substitute elements of a list based on identities

Time:12-22

I have a list like this:

list1 <- as.list(c('a', 'b', 'c', 'd', 'e', 'f'))

and I want to replace all its elements according to this:

new_val <- c('c'=1,'e'=2,'d'=3,'b'=4,'f'=5,'a'=6)

The expected result should be like this:

list3 <- c(6, 4, 1, 3, 2, 5)

I'm trying with different functions as replace() and modifyList() but I'm struggling. Could you help me?

CodePudding user response:

Try

new_val[unlist(list1)]
# a b c d e f 
# 6 4 1 3 2 5 

Use unname, if you don't need a named vector as result:

new_val[unlist(list1)] |> 
  unname()

A fancier way of writing the above using the base pipe operator |>:

list1 |> 
  unlist() |> 
  `[`(x = new_val, i = _) |> 
  unname()

Not sure if it makes the code easier to follow in this example though.

CodePudding user response:

If you change your list back to a character vector, you can use it to index into new_val:

unname(new_val[as.character(list1)])
# 6 4 1 3 2 5

CodePudding user response:

Another way using sapply

sapply(list1, function(x) new_val[x])
a b c d e f 
6 4 1 3 2 5

or unnamed

unname(sapply(list1, function(x) new_val[x]))
[1] 6 4 1 3 2 5
  • Related