How To Select and Save Out Individual Rows From a .csv File More Conveniently

Hello

I have a .csv file with 37 rows and three columns. I am trying to figure out, if it is possible, to write some sort loop that would enable me to select and save out each row individually with file names that would be referenced in one of the columns.

I know how to do it individually, but I hope that I can make this process more efficient with a coding solution instead of having to go one-by-one.

Here is a general example of my data.

accessname <- ("trail1", "trail2", "trail3")
trailtype <- ("mountain", "flat", "hilly")
parking <- ("no", "yes", "no")
trails <- data.frame(accessname, trailtype, parking)

I would like to select each row, and save it out as the name that appears under the "accessname" column i.e., trail1.csv

Thanks for looking

You can do it like this

library(tidyverse)

trails <- data.frame(stringsAsFactors = FALSE,
    accessname = as.factor(c("trail1", "trail2", "trail3")),
    trailtype = as.factor(c("mountain", "flat", "hilly")),
    parking = as.factor(c("no", "yes", "no"))
)

trails %>% 
    group_nest(accessname) %>% 
    pull(data) %>% 
    walk2(trails$accessname, ~write.csv(.x, file = paste0(.y, ".csv"), row.names = FALSE))
1 Like

Wow, thanks that is awesome.

Would it also be possible to do the same writing out GEOJson files for each of the rows using writeOGR?

Thanks again.

As long as you pass the correct parameters through the walk2() function, it should be, Although, I can't give you a concrete example because I'm not familiar with writeOGR()function.

Hello

This solution worked great, however I was wondering if there is a way to (1) not drop the accessname column when the .csv files are written and (2) save to a directory that is not my current working directory.

Thanks so much,

Garrett

Yes, you just need a simple modification

library(tidyverse)

trails <- data.frame(stringsAsFactors = FALSE,
                     accessname = as.factor(c("trail1", "trail2", "trail3")),
                     trailtype = as.factor(c("mountain", "flat", "hilly")),
                     parking = as.factor(c("no", "yes", "no"))
)

trails %>% 
    group_nest(row_number()) %>% 
    pull(data) %>%
    walk2(
        trails$accessname,
        ~write.csv(.x,
                   file = paste0(
                       "path/to/folder/",
                       .y,
                       ".csv"),
                   row.names = FALSE
        )
    )

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