1

Say that I have this lapply:

set.seed(123)
a2 <- lapply(12:14, 
            function(x) {
                a <- data.frame(value=x+round(rnorm(1),1))
                #a$new <- 
                a
            }
)

This produces:

> a2
[[1]]
  value
1  11.4

[[2]]
  value
1  12.8

[[3]]
  value
1  15.6

What I would like is to also have a column with the index number of the list element, so the first would be 1, the second 2, and the third 3. In other words, the number within the [[ ]]. Importantly, I would like to be able to do this all within the lapply.

Note that here is how I would do this using a loop:

for(i in 1:length(a2)) {
    a2[[i]]$new <- i
}

The desired result:

> a2
[[1]]
  value new
1  11.4   1

[[2]]
  value new
1  12.8   2

[[3]]
  value new
1  15.6   3
bill999
  • 2,147
  • 8
  • 51
  • 103

1 Answers1

1

We can use Map on the sequence of the list and cbind

Map(cbind, a2, new = seq_along(a2))

-output

[[1]]
  value new
1  11.4   1

[[2]]
  value new
1  12.8   2

[[3]]
  value new
1  15.6   3

A similar approach with imap

library(purrr)
library(dplyr)
imap(a2, ~ .x %>%
     mutate(new = .y))

Or if we need lapply, loop over the sequence, extract the list element with [[ and transform or cbind

lapply(seq_along(a2), function(i) cbind(a2[[i]], new = i))

-output

[[1]]
  value new
1  11.4   1

[[2]]
  value new
1  12.8   2

[[3]]
  value new
1  15.6   3
akrun
  • 874,273
  • 37
  • 540
  • 662