1

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.

user695426
  • 83
  • 1
  • 4
  • I don't know, but my guess is that unless your file is large (or you have to do this operation thousands of times) you'll be better off doing the 'dumb' thing (reading XLS/writing as CSV). You *might* be able to use `?textConnection` to avoid writing to a file (or maybe `?file`) ... – Ben Bolker Jan 07 '21 at 19:55
  • 2
    It would be easier to help if you provided the specific function in question. If the function requires a path to a CSV file and you can't change the function, you don't really have an option other than to write a CSV file. – MrFlick Jan 07 '21 at 20:00

1 Answers1

1

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

denis
  • 4,710
  • 1
  • 8
  • 33
  • Thanks. I was really hoping to avoid writing the temporary csv but it's starting to seem like the best bet. I was wondering if there was another way when I found you can pass text but it looks like the function needs to be primed for it. Too bad you can't pass "text = read_xlsx" and then escape it from quotes. – user695426 Jan 07 '21 at 20:33
  • I don't think your can do that, but I never dug much either – denis Jan 07 '21 at 20:34