user695426
user695426

Reputation: 133

Is there a way to pass an R object to read.csv?

I have an R function from a package that I need to pass a file path as an argument but it's expecting a csv and my file is an xlsx.

I've looked at the code for the function an it is using read.csv to load the file but unfortunately I can't make any changes to the package.

Is there a good way to read in the xlsx and pass it to the function without writing it to a csv and having the function read it back in?

I came across the text argument for read.csv here: Is there a way to use read.csv to read from a string value rather than a file in R? This seems like might be part way there but as I said I am unable to alter the function.

Upvotes: 1

Views: 235

Answers (1)

denis
denis

Reputation: 5673

Maybe you could construct your own function checking if the file is xlsx, and in this case create a temporary csv file, feed it to your function, and delete it. Something like

yourfunction = function(path){
  read.csv(path)
  head(path)
}

library(readxl)

modified_function = function(path){
  if(grepl{"\\.xlsx",path}){
    tmp <- read_xlsx(path)
    tmp_path <- paste0(gsub("\\.xlsx","",path),"_tmp.csv")
    write.csv(tmp,file = tmp_path)
    output <- yourfunction(tmp_path)
    file.remove(tmp_path)
  }else{
    output <- yourfunction(path)
  }
  return(output)
}

If it is of help, here you can see how to modify only one function of a package: How to modify a function of a library in a module

Upvotes: 1

Related Questions