I'm trying to take a data frame and send it to .csv file(s). Here is my sample data using
dput(df)
df <- structure(list(ident = 1:35, code = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L,
4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("A",
"B", "C", "D", "E", "F"), class = "factor"), Desc = structure(c(3L,
1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 1L), .Label = c("lax", "mia", "nyc"), class = "factor")), .Names = c("ident",
"code", "Desc"), class = "data.frame", row.names = c(NA, -35L
))
filename <- levels(df$code)
filename2 <- paste0(filename, "_file.csv")
lapply
Here is a tidyverse solution:
Since you simply want to use a function for its side effects (writing to a file), and don't need to return any values, the walk function from the purrr package is appropriate here:
library(tidyverse)
walk(unique(df$code), function(x) {write_csv(df %>% filter(code == x), paste0(x, "_file.csv"))})