0

I have multiple tables want to save them as csv with original names. Here is my example : df.a01,df.a02,df.a03,etc.

I tried

list <- list(df.a01,df.a02,df.a03)

for (i in 1:length(list)) {
  write.csv(list[i], paste0(i, '.csv'), row.names = FALSE)
}

but it's not work.

I got 1.csv,2.csv,3.csv,but I want to is like a01.csv,a02.csv,a03.csv.

I also tried Save several data frames with different names with loop, still can't get what I desired.

Any help would be greatly appreciated.

mashimena
  • 165
  • 6

1 Answers1

0

Note that it is not regarded as good practice to convert variable names into string, even if it is possible (e.g. this thread).

But this is not your main problem : when you define your list, you do not set name to its elements, so the variable name are "lost" (take a look at your list to see it : names(list)).

Lastly, you shouldn't use a function name to define a variable. list is a function in R (which is used to build... list) : as you're replacing it with you're new variable, you cannot use anymore the function.

A good workflow for setting name variables and using them in a loop would look like something like this :

l = list()

l["df1"] = data.frame(t = c(1,2,3))
l["df2"] = data.frame(t = c(1,2,3))
l["df3"] = data.frame(t = c(1,2,3))

for (i in 1:length(l)){
  write.csv(l[[i]], paste0(names(l)[i], '.csv'), row.names = FALSE)
}

Hope this helps

cyrilb38
  • 924
  • 6
  • 17