Home > front end >  In R, how to dynamically change the .csv file name based on a variable?
In R, how to dynamically change the .csv file name based on a variable?

Time:09-08

I want to dynamically change the "reporter_name" text in write.xlsx( myfile, file = "reporter_name.csv") whenever I save my .csv file based on the country reporter name.

e.g. if my variable reporter_name="Thailand" it automatically saves as write.xlsx( myfile, file = "Thailand.csv")

Is there a quick way to do this?

The reporter name is inputted at the start of the script and I would like to have the output automatically saved without having to edit anything else later, so that it doesn't for instance overwrite the previous country file if I forget to change it.

CodePudding user response:

You can use deparse & substitute to return the name of an object.

reporter_name <- c("Thailand","England")

Thailand <- data.frame(x1 = c(1,2,3),
                       x2 = c(3,5,6))

England <- data.frame(x1 = c(41,21,31),
                      x2 = c(31,55,61))

save_my_excel <- function(reporter_name){
  filename <- paste0(reporter_name, ".xlsx")
  data <- get(reporter_name)
  writexl::write_xlsx(data, filename)
}


lapply(reporter_name, save_my_excel)

CodePudding user response:

Assuming that data is the R data frame that you want to write:

# 1
write.xlsx(data, file = paste0(reporter_name, ".xlsx"))

# 2
write.xlsx(data, file = sprintf("%s.xlsx", reporter_name))

# 3
library(gsubfn)
fn$write.xlsx(data, file = "`reporter_name`.xslx")

Note

reporter_name <- "Thailand"
  • Related