简体   繁体   中英

Writing data by groups while skipping the group column

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM