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