Ryan John Ryan John - 1 year ago 36
R Question

Parse data frame producing CSV with lapply

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
))


I'm trying to loop through my data and select only A and output to file.

filename <- levels(df$code)

filename2 <- paste0(filename, "_file.csv")


Would I use
lapply
to write a file for each code? Any help would be appreciated!

Answer Source

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"))})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download