Say you have a list of data.frames that already exist in the environment:
library(magrittr)
lapply(
paste0("z", 2011:2015),
function(x) assign(
x,
data.frame(x=rnorm(10),y=rnorm(10)),
pos = 1
)
)
# should create z2011 through z2015 in your R env
What I would like to do is: extract a column, combine these into one data.frame, then add an additional variable to identify where they came from using magrittr syntax.
I realize this is something trivial using other techniques (namely: ldply(list)
, rbind.fill(listing)
, rbind_all(listing)
, do.call(rbind,...)
). The point of my question is to understand approaches using magrittr
syntax.
df <-
paste0("z",2011:2015) %>%
lapply(get) %>%
lapply(function(x) extract2(x,"x")) %>%
# what would you do next? Another approach you think is
# more appropriate for magrittr?
I don't know how to add a new variable. For examples sake, I would like to end up with the following:
do.call(
rbind,
lapply(
paste0("z",2011:2015),
function(x) {
data.frame(x = get(x)$x, year = x)
}
)
)