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.
CodePudding user response:
We can use
library(dplyr)
library(purrr)
mtcars %>%{
split(.[-10], .$gear)
} %>%
imap(~ write.table(.x, paste0(.y, "_.txt"),
sep = "\t", row.names = FALSE, col.names = FALSE))
CodePudding user response:
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.