Using different named dataframes in loops

Hi,

I am importing different dataframes from two different excel groups, and I would like to put them all together in different dataframes using loops. The problem is that I don't know how to call the dataframes bases already inside the loop.

files = c("men.xlsx", "women.xlsx")
names = c("men", "women")
names_def = c("men_def", "women_def")
years = as.character(2010:2020)
men_def= list()
women_def= list()

for (j in seq_along(years)) {
for (i in seq_along(files)) {
  assign(names[i], read_excel(path = files[i], sheet=years[j]))
  assign(names_def[i], rbind(names[[i]],  names_def[[i]]))
}
}

The objective is that at the end of the loop you have two dataframes with all the information of all the years, but when using rbind in this way it does not replace by the name of the dataframe as I would like. But the final result is a 2x1 vector where, men_def="men", "men_def", and women_def="women", "women_def".

In other software I would use something like:

foreach i in $list {
append using`i' 
}

Thanks!

Hi Felipe, welcome to the community!

If you want to access a defined variable using string, you can't use it directly. You have to use get, or mget for multiple variables. This is the issue in 2nd assign call.

Let us know if you still face the issue after fixing for this. If you do, can you share a reproducible example?

It worked perfectly, thank you very much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.