0

Edited for clarity and reproduciblity....

I have a list of dataframes that I want to export to a folder on my PC via a file path. Doing this one at a time, or writing multiple 'write.csv' commands is possible, but repetitive. Is there a way that I could use a for loop to export my data frames from that list using a single command?

example data:

m1 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
               75, 10, 36, 36, 23, 55, 56, 24, 22, 66,
               -7.8, -5.6, -2, -4.1, -8.4, -3, -4.2, -4, 0.1, -3), nrow = 10) 
df <- as.data.frame(m1)  
split_n <- 5 
dlist <- split(df, factor(sort(rank(row.names(df))%%split_n))) 
names(dlist) <- paste0("site_data", 1980:1984)
dlist

I can do the following, one file at a time:

write.csv(dataList$table_1,"C:/filepath/dataframe_name_1.csv", row.names = F)

But doing this for hundreds of files isn't exactly efficient.

What I want to do is send the five data frames (site_data1980 : site_data1984) along my filepath to the folder on my PC as a list of named csv files.

2 Answers 2

1
lapply(seq_along(dataList), \(i) write.csv(dataList[[i]], paste0("C:/filepath/dataframe_name_", i, ".csv"), row.names = F))
Sign up to request clarification or add additional context in comments.

3 Comments

There is some error in this. I get a warning "unexpected '\'" and "expected ',' after expression"
Which version of R do you use?
Replace \(i) with function(i)
0

You could try something like this

filepath <- "C:/filepath/dataframe_name_"

purrr::imap(dlist, ~write.csv(x = .x, file = paste0(filepath,  
                              readr::parse_number(.y), ".csv"), 
                              row.names = FALSE))

6 Comments

This does two strange things. Firstly it only saves the first 8 out of 31 files. Secondly it converts the data frame contents into a single column in the output csv files.
Bob, have a look at this. It is very difficult to help you, when we have limited information. For instance could you post dput(dataList$table_1) and maybe an example dataframe such that we can reproduce your issue.
Understood. Reproducible example added to my question.
check my edit, for the MWE it works.
It works, thanks. I do wonder, the files are saved as "file1.csv, file2.csv" etc. Is there a way to replace the "1","2", with year numbers to match the names in the list?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.