rfunction

How to write as a file each separate row in the dataframe, with file names indicated in a separate data frame?


I would like to be able to write each separate row of a dataframe into a file, with a file name being indicated in the corresponding index entry of a different data frame. Here is the data frame for which I'd like to save rows as files:

data1_sim <- data.frame(band = c("Pink Floyd", "Queen", "Kanye West"), song = c("Shine on You Crazy Diamond", "My Melancholic Blues", 
                                                                                "Pablo Saint"), Album=c("Album1", "Album2", "Album3"),
                                                                                review=c("Live on, you crazy Diamond!", 
                                                                                         "I'm forever in your dept, Queen!",
                                                                                         "Both crazy and in dept, can't compete with that!"))

Here is the vector of file names:

file_names <- paste0(data1_sim$band, "_", data1_sim$song)

I tried to use both for cycle and a function apply (function obviously would be a much better solution). Here is the code I tried:

list_files1 <- lapply(1:nrow(data1_sim), 
                     function(i) write.table(data1_sim[i,],
                                             file = file_names[i],
                                             row.names = FALSE, col.names = FALSE,
                                             sep = "\t"))

But it gives out a list of empty entries. What's the problem?


Solution

  • Try

    file_names = with(data1_sim, paste0(band, "_", song, ".csv"))
    lapply(seq(nrow(data1_sim)), \(i) write.table(data1_sim[i, ], file_names[i])) |>
      invisible() # optional
    

    or choose a different file format (cp. ".csv"). At least on Mac OS, write.table works without any ending.