Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute elements of a list based on identities

Tags:

list

r

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?

like image 305
Carpa Avatar asked Oct 16 '25 04:10

Carpa


2 Answers

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.

like image 98
markus Avatar answered Oct 17 '25 17:10

markus


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
like image 42
zephryl Avatar answered Oct 17 '25 18:10

zephryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!