Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify elements of a nested list in base R without loops

I have a nested list with two or more elements at the top level and want to modify named elements of the sub-lists, e.g. by appending values from a named vector.

Let’s assume L is a list of two elements and Nis a vector with the same number of elements:

L <- list(
  foo = list(
    x1=1,
    x2=c(a=1, b=2)
  ),
  bar = list(
    x1=2,
    x2=c(e=2, f=3)
  )
)

N <- c(n=11, n=12)

Then I want to get a result like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list(
  foo = list(
    x1=1,
    x2=c(a=1, b=2, n=11)
  ),
  bar = list(
    x1=2,
    x2=c(e=2, f=3, n=12)
  )
)

It is easy to read the elements of the sub-lists:

lapply(L, "[[", "x2")

So I wonder if there is a similarly compact way to change elements.

>Solution :

We may use Map to loop over the L, and corresponding elements of N, extract the ‘x2’ component and append the N values and assign back, return the object (x)

L2 <- Map(\(x, y) 
          {
          x$x2 <- c(x$x2, n=y)
          x
          }, L, N)

-checking with OP’s output

> all.equal(L2, out)
[1] TRUE

Or a variant is to assign with the name

Map(\(x, y) {x$x2['n'] <- y; x}, L, N)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading