Reputation: 1
I am learning R and was looking for a way to make the same data transformation across multiple dataframes, for example, recoding a variable that appears in each dataframe, without having to type out the code each time for each dataframe. I created a list of the dataframes and then used lapply() to transform them all in one function, however, the result was stored in a new list. I would like to be able to now extract each one of those list elements into their own dataframes, named the same way as the originals. Does anyone know how to do that?
Here is some example code:
testlist<-list(FY2012First,FY2012Last)
testlist<-lapply(testlist, function(q) {
q<-mutate(q,
YearsofServiceCat =
ifelse(YearsatAgency<=2, "0-2",
ifelse(YearsatAgency>=3 & YearsatAgency<=5,"3-5",
ifelse(YearsatAgency>=6 & YearsatAgency<=8,"6-8",
ifelse(YearsatAgency>=9,"9 or greater",
"Unknown"))))))}
This gives me a new list with each element updated as I want, but now I want to get those elements back into individual dataframes named "FY2012First" and "FY2012Last". I used this to do it individually:
FY2012FirstNew<-as.data.frame(list["FY2012First"])
However, in FY2012FirstNew, each variable is now named "FY2012First.(variable name)", and I don't want that, they should just be named "(variable name)."
So the question is really two-fold; is there a better way to extract those dataframes, and is there a way to do it without the variable renaming?
Upvotes: 0
Views: 329
Reputation: 4846
data(iris)
data(mtcars)
iris2 = iris
mtcars2 = mtcars
testlist = list(iris2 = iris, mtcars2 = mtcars)
testlist = lapply(testlist, function(dfs){
dfs$new_col = 1
dfs
})
# datasets are unchanged
str(iris2)
str(mtcars2)
rm(list = names(testlist))
list2env(testlist, baseenv())
# datasets are updated
str(iris2)
str(mtcars2)
Upvotes: 1
Reputation: 41
There is probably a better way, but I would use for loop:
for (i in 1:length(testlist)) {
assign(names(testlist)[i], testlist[[i]])
}
Upvotes: 0