(R) Finding list elements by name and combine list elements into c()

36 Views Asked by At

I have an S4 object named "S4" that contains the id and a list (or it can be changed into a data frame) named "color" that has the color information annotated to each id in R.

# S4 information - id: This is a printed example on my console
# S4@name$id 
# [1] "A" "B/b" "B/b" "C"

# Color list
color = list(
"A" = "red", 
"B/b" = "yellow", 
"C" = "blue")

I want to put all of the color names matched to the id to call the list elements of all the matched colors (ex. c("red", "yellow", "yellow")).

For formatting ids into a combined id names (ex. c("A", "B/b", "B/b", "C")), I tried the code below:

color = list(
"A" = "red", 
"B/b" = "yellow", 
"C" = "blue")

id <- c("A", "B/b", "B/b", "C") # this is a example to make id characters.

# cat(paste0('"', paste(id, collapse="\", \""), '"')) is to print all the ids with comma, but it is actually containing "\".
color[c(cat(paste0('"', paste(id, collapse="\", \""), '"')))]

This code is not working, and I wonder how I can revise the code to get all the ids into a combined characters to call the matched list elements of color names into a combined characters as same as id.

So final results would be:

# id information: c("A", "B/b", "B/b", "C") in the "color" list 
# Color list elements: c("red", "yellow", "yellow", "blue") to put all color names into another function

Any better approach would be great.

Thanks in advance!

0

There are 0 best solutions below