Writing data by groups while skipping the group column

Viewed 42

I want to write the data frame in separate files by its groups but at the same time I don't want to the files to have the column which contains the group info.

For example, in the code below, I don't want the gear column in each separate file.

library(dplyr)

mtcars |> 
  group_by(gear) |> 
  do(write.table(., paste0(unique(.$gear), "_.txt"),
               sep = "\t", row.names = F, col.names = F))

Any ideas? Thanks.

2 Answers

We can split by the 'gear' column and use imap to loop over the named list for writing

library(dplyr)
library(purrr)
mtcars %>%{
   split(.[-10], .$gear)
    } %>%
   imap(~ write.table(.x, paste0(.y, "_.txt"),
   sep = "\t", row.names = FALSE, col.names = FALSE))

If we want to return the dataset after writing, can also use group_modify

mtcars %>% 
  group_by(gear) %>% 
  group_modify(~  {
   write.table(.x, paste0(.y, "_.txt"),
   sep = "\t", row.names = FALSE, col.names = FALSE)
  .x})

We could also use the (experimental) group_walk:

library(dplyr)

mtcars |>
 group_by(gear) |>
 group_walk(~ write.table(.x,
                          file = paste0(.y$gear, "_.txt"),
                          sep = "\t",
                          row.names = FALSE,
                          col.names = FALSE)
            )

.y to refer to the key

.x to refer to the subset of rows of .tbl for the given group.

The parameter .keep is FALSE by default.

Related