Home > Net >  R: creating multiple dataframes using for loop is only storing final dataframe to list
R: creating multiple dataframes using for loop is only storing final dataframe to list

Time:01-06

I am trying to create multiple named dataframes using a for loop. A simplified version of the code I am using is below. I would like to keep the structure of the loop as similar as possible as it is needed for the more complex analysis I am doing. The problem I am having is that only the last dataframe is being stored to the list. All other items in the list are empty. What is causing this behavior and how can I edit the code to fix it?

dfs = list()
df.names = c("a", "b", "c")
for (i in length(df.names)) {
  df = data.frame()
  tmp = data.frame(x = 1, y = 2, z = 3)
  df = rbind(df,tmp)
  dfs[[i]] = df
}
names(dfs) = df.names

CodePudding user response:

Your for loop should be:

for (i in 1:length(df.names))

as length(df.names) is a single value (3). As you have it, it reads "for i in 3".

As mentioned in the comments, you can also use:

for (i in seq_along(df.names))

This has the added benefit that the loop won't execute rather than throwing an error if df.names is empty.

  •  Tags:  
  • Related