TransWikia.com

Appending a list in a list using a for loop

Stack Overflow Asked by Syed Ahmed on November 22, 2021

I’m a beginner in R and I’m facing a rather simple issue. I need to create a list of a list iteratively with the data that is given below.

# First Vertical layer
P01<- list("S17","S18")
P02<- list("S1","S2")
P03<- list("S3","S4")

P1 <- list(P01, P02, P03)
# Second Vertical layer
P2 <- list("S22","S11","S12")

For each list in P1, I need to append it to the start of each value in P2 and record it in a list. What I need:

lt <- list(list("S17", "S18", "S22"),list("S17", "S18", "S11"),list("S17", "S18", "S12"), list("S1", "S2", "S22"), ....)

What I have written so far (but doesn’t work):

for (val in P1){
  for (lev in P2){
    J <- append(val,lev)
  }
}

I’m coming from a python background and this syntax and data type is becoming a bit problematic for me in R. Any help would be sufficient.

2 Answers

If the order does not matter you can use expand.grid and than unlist the result in lapply:

x <- lapply(asplit(expand.grid(P1, P2), 1), function(x) as.list(unlist(x)))
x[1:2]
#[[1]]
#[[1]]$Var11
#[1] "S17"
#
#[[1]]$Var12
#[1] "S18"
#
#[[1]]$Var2
#[1] "S22"
#
#
#[[2]]
#[[2]]$Var11
#[1] "S1"
#
#[[2]]$Var12
#[1] "S2"
#
#[[2]]$Var2
#[1] "S22"

And in case order matters:

x <- lapply(asplit(rev(expand.grid(P2, P1)), 1), function(x) as.list(unlist(x)))
x[1:2]
#[[1]]
#[[1]]$Var21
#[1] "S17"
#
#[[1]]$Var22
#[1] "S18"
#
#[[1]]$Var1
#[1] "S22"
#
#
#[[2]]
#[[2]]$Var21
#[1] "S17"
#
#[[2]]$Var22
#[1] "S18"
#
#[[2]]$Var1
#[1] "S11"

Answered by GKi on November 22, 2021

A one-liner base R solution.

lapply(P1, function(x) lapply(P2, function(y) c(unlist(x), y)))

Answered by Rui Barradas on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP