Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

Adding elements to a list according to another list in R

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.

question from:https://stackoverflow.com/questions/65901778/adding-elements-to-a-list-according-to-another-list-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...