R: concatenate the values of the components of a list with another list specifying which ones go together
I have two lists. lst1
contains symbolic vectors that 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 lst1
contain one or more variable names. lst2
contains 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 a product of previous code that I have dealt with. I would like to get a list like lst1
, where instead of variable names, each component contains its 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 maybe get only sorted unique values in each component. How can I do that?
EDIT: I updated the post in the section where I provide an example for lst3
, because I noticed bugs in lst3
.
source to share
Try
lapply(lst1, function(x) sort(unique(unlist(lst2[x], use.names=FALSE))))
If we don't need sort
and get the valuesunique
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"
source to share