program story

큰 xlsx 파일을 R로 가져 오시겠습니까?

inputbox 2020. 11. 7. 09:28
반응형

큰 xlsx 파일을 R로 가져 오시겠습니까?


"큰"xlsx 파일 (~ 20Mb)에서 데이터를 가져 오는 방법을 아는 사람이 있는지 궁금합니다. xlsx 및 XLConnect 라이브러리를 사용하려고했습니다. 불행히도 둘 다 rJava를 사용하고 항상 동일한 오류가 발생합니다.

> library(XLConnect)
> wb <- loadWorkbook("MyBigFile.xlsx")
Error: OutOfMemoryError (Java): Java heap space

또는

> library(xlsx)
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
   java.lang.OutOfMemoryError: Java heap space

또한 rJava를로드하기 전에 java.parameters를 수정하려고했습니다.

> options( java.parameters = "-Xmx2500m")
> library(xlsx) # load rJava
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
   java.lang.OutOfMemoryError: Java heap space

또는 rJava를로드 한 후 (이것은 약간 어리석은 것 같습니다) :

> library(xlsx) # load rJava
> options( java.parameters = "-Xmx2500m")
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
   java.lang.OutOfMemoryError: Java heap space

그러나 아무것도 작동하지 않습니다. 누구나 아이디어가 있습니까?


누군가가 분석을 위해 나에게 (아직 다른) Excel 파일을 보냈을 때이 질문을 우연히 발견했습니다. 이것은 그다지 크지 않지만 어떤 이유로 든 비슷한 오류가 발생했습니다.

java.lang.OutOfMemoryError: GC overhead limit exceeded

이전 답변에서 @Dirk Eddelbuettel의 의견을 바탕으로 openxlsx 패키지 ( http://cran.r-project.org/web/packages/openxlsx/ )를 설치했습니다 . 그리고 다음을 실행했습니다.

library("openxlsx")
mydf <- read.xlsx("BigExcelFile.xlsx", sheet = 1, startRow = 2, colNames = TRUE)

내가 찾던 것 뿐이었다. 사용하기 쉽고 사악합니다. 나의 새로운 BFF입니다. 팁 @Dirk E에 감사드립니다!

BTW, 나는 Dirk E 로부터이 답변을 밀고 싶지 않으므로 그가 답변을 게시하면 내 대신 수락하십시오!


options(java.parameters = "-Xmx2048m")  ## memory set to 2 GB
library(XLConnect)

Java 구성 요소가로드되기 전에 "옵션"을 사용하여 더 많은 메모리를 허용합니다. 그런 다음 XLConnect 라이브러리를로드합니다 (Java 사용).

그게 다야. readWorksheet .... 등으로 데이터 읽기를 시작합니다. :)


@orville jackson 응답에 동의하며 저도 정말 도움이되었습니다.

@orville jackson이 제공 한 답변에 대한 인라인. 다음은 큰 파일을 읽고 쓰기 위해 openxlsx사용하는 방법에 대한 자세한 설명입니다 .

데이터 크기가 작을 때 R에는 요구 사항에 따라 활용할 수있는 많은 패키지와 기능이 있습니다.

write.xlsx, write.xlsx2, XLconnect 도 작업을 수행하지만 때때로 openxlsx에 비해 느립니다.

따라서 대용량 데이터 세트를 처리하고 Java 오류가 발생하면. 정말 멋진 "openxlsx"를 보시고 1/12로 시간을 단축 할 것을 제안합니다.

나는 모든 것을 테스트했고 마침내 openxlsx 기능의 성능에 깊은 인상을 받았습니다.

다음은 여러 데이터 세트를 여러 시트에 쓰는 단계입니다.

install.packages("openxlsx")
library("openxlsx")

start.time <- Sys.time()

# Creating large data frame
x <- as.data.frame(matrix(1:4000000,200000,20))
y <- as.data.frame(matrix(1:4000000,200000,20))
z <- as.data.frame(matrix(1:4000000,200000,20))

# Creating a workbook
wb <- createWorkbook("Example.xlsx")
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe

Sys.setenv ( "R_ZIPCMD"= "C : /Rtools/bin/zip.exe")는 Rtools에서 일부 유틸리티를 참조하므로 정적이어야합니다.

참고 : 시스템에 Rtools가 설치되어 있지 않은 경우 원활한 경험을 위해 먼저 설치하십시오. 여기에 참조 용 링크가 있습니다 : (적절한 버전 선택) https://cran.r-project.org/bin/windows/Rtools/

아래 링크에 따라 옵션을 확인하십시오 (설치하는 동안 모든 확인란을 선택해야 함) https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

# Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
addWorksheet(wb, "Sheet 3")

# Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

writeData(wb, 1, x)

# incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
writeData(wb, 2, x = y, withFilter = TRUE)

## Similarly writeDataTable is another way for representing your data with table formatting:

writeDataTable(wb, 3, z)

saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

openxlsx 패키지는 엑셀 파일에서 /에서 방대한 데이터를 읽고 쓰는 데 정말 좋으며 Excel 내에서 사용자 지정 서식 지정을위한 많은 옵션이 있습니다.

흥미로운 사실은 여기서 자바 힙 메모리에 대해 신경 쓸 필요가 없다는 것입니다.


As mentioned in the canonical Excel->R question, a recent alternative which has emerged comes from the readxl package, which I've found to be quite fast, compared with, e.g. openxlsx and xlsx.

That said, there's a definite limit of spreadsheet size past which you're probably better off just saving the thing as a .csv and using fread.


I know this question is a bit old, but There is a good solution for this nowadays. This is a default package when you try to import excel in Rstudio with GUI and It works well in my situation.

library(readxl)

data <- read_excel(filename)

I also had the same error in both xlsx::read.xlsx and XLConnect::readWorksheetFromFile. Maybe you can use RODBC::odbcDriverConnect and RODBC::sqlFetch, which uses Microsoft RODBC, which is much more efficient.


@flodel's suggestion of converting to CSV seems the most straightforward. If for whatever reason, that's not an option, you can read in the file in chunks:

 require(XLConnect)
 chnksz <- 2e3
 s <- <sheet>
 wb <- loadWorkbook(<file>, s)
 tot.rows <- getLastRow(wb)
 last.row =0
 for (i in seq(ceiling( tot.rows / chnksz) )) {
    next.batch <- readWorksheet(wb, s, startRow=last.row+i, endRow=last.row+chnksz+i)
    # optionally save next.batch to disk or 
    # assign it to a list. See which works for you. 
 } 

I found this thread looking for an answer to the exact same question. Rather than try to hack an xlsx file from within R what ended up working for me was to convert the file to .csv using python and then import the file into R using a standard scanning function.

Check out: https://github.com/dilshod/xlsx2csv

참고URL : https://stackoverflow.com/questions/19147884/importing-a-big-xlsx-file-into-r

반응형