Home > front end >  Create for each match an own csv
Create for each match an own csv

Time:11-10

I've alreaedy looked for a similar question to mine but I couldn't found it. Whenever you find one, let me know.

I have a df that looks like (in reality this df has three columns and more than 1000 rows):


Name, Value
Markus, 2
Markus, 4
Markus, 1
Caesar, 77
Caesar, 70
Brutus, 3
Nero, 4
Nero, 9
Nero, 10
Nero, 19

How can I create for each match (depending on Name) an own csv file? I don't know how to approach this.

In this case the end result should be four csv files with the name form the Name column:

Markus.csv
Caesar.csv
Brutus.csv
Nero.csv

I'm thankful for any advice.

CodePudding user response:

We can split your df by Name to create a list, iterate over it and write a csv for each group. File names are created using paste0

lst <- split(df, df$Name)
lapply(1:length(lst), function(i){
  write.csv(lst[[i]], paste0(names(lst)[i], ".csv"), row.names = FALSE)
})

CodePudding user response:

Similar idea to u/Jilber Urbina, you can use dplyr and tidyr to filter the dataset. The basic principle for both answers is to iterate the write.csv() function over the list/vector of names via lapply() function.

library(dplyr)
library(tidyr)

lapply(unique(df$Name), function(i) {
  write.csv(
    x = df %>% dplyr::filter(Name==i) %>%  # filter dataset by Name
      select(-Name),                       # if you want to remove the Name column from output
    file = paste0(i,'.csv'),
    row.names = FALSE
  )
})
  •  Tags:  
  • r
  • Related