[英]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.
我查看了 function 的代碼,它正在使用 read.csv 加載文件,但不幸的是我無法對 package 進行任何更改。
有沒有一種很好的方法來讀取 xlsx 並將其傳遞給 function 而無需將其寫入 csv 並讓 function 讀回它?
我在這里遇到了 read.csv 的文本參數: Is there a way to use read.csv to read from a string value rather than a file in R? 這似乎可能是其中的一部分,但正如我所說,我無法更改 function。
也許您可以構建自己的 function 檢查文件是否為xlsx
,在這種情況下創建一個臨時csv
文件,將其提供給您的 function 並刪除它。 就像是
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)
}
如果有幫助,您可以在此處查看如何僅修改 package 的一個 function: How to modify a function of a library in a library
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.