Adding elements to a list according to another list in R

Viewed 41

I would like to call the elements of one list (y) according to their name to append it in another (x). The y list does not necessarily contain all the different elements of x. Those two lists look like these:

> x
$a
[1] "c" "d" "e"

$b
[1] "f" "g" "h"

> y
$c
[1] 10 11 12

$d
[1] 20 21 22

$f
[1] 40 41 42

$g
[1] 50 51 52

The desired output is:

> z
$a
[1] "c"  "d"  "e"  "10" "11" "12" "20" "21" "22"

$b
[1] "f"  "g"  "h"  "40" "41" "42" "50" "51" "52"

I came out with this solution:

for (i in 1:length(x)){
  for (j in 1:length(x[[i]])){
    if (ifelse(isTRUE(x[[i]][j] == names(y[x[[i]][j]])), TRUE, FALSE)){
      new <- y[[x[[i]][j]]]
      z[[i]] <- c(z[[i]], new)
    }
  }
}

But I would have liked to know if the same thing could have been done with lapply(x, function(x) something) in a more efficient way perhaps.

2 Answers

You can use lapply with c and unlist:

lapply(x, function(i) c(i, unlist(y[i], use.names = FALSE)))
#$a
#[1] "c"  "d"  "e"  "10" "11" "12" "20" "21" "22"
#
#$b
#[1] "f"  "g"  "h"  "40" "41" "42" "50" "51" "52"

Data:

x <- list(a = c("c", "d", "e"), b = c("f", "g", "h"))
y <- list(c = 10:12, d = 20:22, f = 40:42, g = 50:52)

Or using map from purrr

library(purrr)
map(x, ~ c(.x, flatten_chr(y[.x])))

-output

#$a
#[1] "c"  "d"  "e"  "10" "11" "12" "20" "21" "22"

#$b
#[1] "f"  "g"  "h"  "40" "41" "42" "50" "51" "52"

data

x <- list(a = c("c", "d", "e"), b = c("f", "g", "h"))
y <- list(c = 10:12, d = 20:22, f = 40:42, g = 50:52)
Related