0

I'm still learning the ropes of R. I have a question about using the write.csv function in a user-defined function to create uniquely named exportable csvs.

For example:

pie_final <- function(num_animal) {
  anim_prac <- animal[num_animal]
  out_anim <- capture.output(anim_prac)
  out_final_calc <- as.character(strsplit(out_anim, " ")[[1]][2]) 
  samp_anim <- registry[(registry$Animal == anim_prac),]
  out_final_calc
}

pie_final_2 <- function(num_animal) {
  anim_prac_2 <- animal[num_animal]
  out_anim_2 <- capture.output(anim_prac_2)
  out_final_calc_2 <- as.character(strsplit(out_anim_2, " ")[[1]][2]) 
  samp_anim_2 <- registry[(registry$Animal == anim_prac_2),]
  samp_dis
}

csv_name <- function(x){
  (write.csv(
    do.call(
      "<-", 
      list(pie_final(x), pie_final_2(x))
    ), 
    cat(sprintf("file=\"%s.csv\"", pie_final(x)))
  ))
}  

The first two functions work correctly. However, I'm hoping that the csv_name function will output a written csv file using the write.csv function with a unique name each time. For example, I am hoping the file = argument in the write.csv function will print pie_final(x) (which is a string) followed by .csv.

When I run the function, I get the following error.

file="Falcon.csv"
Error in if (file == "") file <- stdout() else if (is.character(file)) { : argument is of length zero 

So, it seems like the second argument for the write.csv function is being produced (file = "Falcon.csv"), but it doesn't seem to be inserted correctly to execute the entire write.csv function.

My ultimate goal is to have the final function produce uniquely-named exportable csv files.

Do you know how to get around this issue?

alistaire
  • 38,696
  • 4
  • 60
  • 94
  • 1
    `do.call(" – alistaire Jul 18 '19 at 03:17
  • Thanks. I added in the gsub function in place of the cat and sprintf functions, and the code works when run outside of a function. However, inside a function, it writes a file that isn't a csv, but a plain "file." Do you know why that would be? – Adam Young Jul 18 '19 at 17:50

0 Answers0