3

I have two lists. lst1 contains character vectors which represent variable names:

lst1 <- list(c("var1", "var2"),
             "item1",
             c("var12", "var15", "var17"),
             c("item3", "item5", "item7"),
             "var22",
             c("var27", "var29", "var33", "var34"))

As you can see some components in lst1 contain one or more variable names. lst2contains values for each variable name in lst1, but each in a separate component:

lst2 <- list(var1 = as.character(c(1, 2, 3, 5, 6)),
             var2 = as.character(c(1, 3, 4, 5, 6, 7)),
             item1 = letters[1:5],
             var12 = as.character(1:3),
             var15 = as.character(1:5),
             var17 = as.character(1:6),
             item3 = letters[3:8],
             item5 = letters[4:9],
             item7 = letters[5:10],
             var22 = as.character(2:7),
             var27 = as.character(4:10),
             var29 = as.character(3:8),
             var33 = as.character(1:4),
             var34 = as.character(4:9))

These two lists are much larger and are product of previous code I have dealt with. What I would like to achieve is to obtain a list as lst1 where instead of the variable names each component contains their concatenated elements from lst2 for all names that belong to that component in lst1, something like

lst3 <- list(c("1", "2", "3", "5", "6", "1", "3", "4", "5", "6", "7"),
             c("a", "b", "c", "d", "e"),
             c("1", "2", "3", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "6"),
             c("c", "d", "e", "f", "g", "h", "d", "e", "f", "g", "h", "i", "e", "f", "g", "h", "i", "j"),
             c("2", "3", "4", "5", "6", "7"),
             c("4", "5", "6", "7", "8", "9", "10", "3", "4", "5", "6", "7", "8", "1", "2", "3", "4", "4", "5", "6", "7", "8", "9"))

and possibly to obtain just the sorted unique values in each component. How could this be done?

EDIT: I have updated my post in the section where I give an example for lst3 because I spotted mistakes in lst3.

panman
  • 1,179
  • 1
  • 13
  • 33

1 Answers1

2

Try

lapply(lst1, function(x) sort(unique(unlist(lst2[x], use.names=FALSE))))

If we don't need to sort and get the unique values

lapply(lst1, function(x) unlist(lst2[x], use.names=FALSE))
#[[1]]
#[1] "1" "2" "3" "5" "6" "1" "3" "4" "5" "6" "7"

#[[2]]
#[1] "a" "b" "c" "d" "e"

#[[3]]
#[1] "1" "2" "3" "1" "2" "3" "4" "5" "1" "2" "3" "4" "5" "6"

#[[4]]
#[1] "c" "d" "e" "f" "g" "h" "d" "e" "f" "g" "h" "i" "e" "f" "g" "h" "i" "j"

#[[5]]
#[1] "2" "3" "4" "5" "6" "7"

#[[6]]
#[1] "4"  "5"  "6"  "7"  "8"  "9"  "10" "3"  "4"  "5"  "6"  "7"  "8"  "1"  "2" 
#[16] "3"  "4"  "4"  "5"  "6"  "7"  "8"  "9" 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Wow, this was not just fast, this was blazing fast. Works like charm. Thank you very much! – panman May 25 '15 at 15:37