I would like to write separate csv's from one dataframe, but the csv's should be named after a grouping variable and only contain 3 specific columns (among potentially many). Does anyone have any tips?
Here's a minimal example. What I'd like to do is write a csv for each subject_nr (named "101.csv", "102.csv", etc.) where the csv's only contain the columns item, start_time, and end_time for the relevant subject_nr.
df <- data.frame("subject_nr" = c("101", "101", "101", "102", "102", "103", "103", "103"),
"item" = c("a", "b", "c", "a", "b", "a", "b", "c"),
"start_time" = c(50, 52, 55, 53, 54.5, 12, 15, 17),
"end_time" = c(51, 54, 60, 53.5, 55.5, 14, 16.5, 19),
"extra_variable"= c("s", "t", "u", "v", "w", "x", "y", "z"))
For example, the resulting csv ("101.csv") for the first subject_nr (101) should look like (with no line numbering or anything like that):
"item","start_time","end_time"
"a",50,51
"b",52,54
"c",55,60
CodePudding user response:
lst <- split(df[, c("item","start_time","end_time")], df$subject_nr)
lapply(seq_along(lst), function(i){
write.csv(lst[[i]], paste0(names(lst)[i], ".csv"), row.names=FALSE)
})