'output of group_split needs to be saved as separate dataframe
I have split my data frame using group_split and further want to save outputs as a separate csv. I am using the following code. I am unable to get those csv. Please help. Thank you.
library(dplyr)
y<-year_x %>% group_split(Year)
for(i in 1:length(y)) {
write.csv2(get(y[i]),
paste0("D:/newfolder",
y[i],
".csv"),
row.names = FALSE)
Solution 1:[1]
group_split will not return you name of the year as list name. Use base::split instead.
y <- split(year_x, year_x$Year)
for(i in seq_along(y)) {
write.csv2(y[[i]], paste0("D:/newfolder/", names(y)[i], ".csv"),row.names = FALSE)
}
You could also do this with purrr::imap
purrr::imap(y, ~write.csv2(.x, paste0("D:/newfolder/", .y, ".csv"),row.names = FALSE))
Solution 2:[2]
We can use group_map
library(dplyr)
library(purrr)
library(stringr)
year_x %>%
group_by(year_x) %>%
group_map(~ write.csv2(.x, file.path("D:/newfolder/", str_c(cur_group(), ".csv")), row.names = FALSE))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ronak Shah |
| Solution 2 | Amar |
