문제 설명
xlx의 각 시트에서 특정 셀을 추출하기 위해 이 R 코드를 개선하는 데 도움이 필요합니다. (I need help to improve this R code to extract specific cell from each sheet in xlxs)
Excel 파일의 각 시트에서 첫 번째 열과 세 번째 행 셀을 추출한 다음 하나의 데이터 프레임으로 결합하는 코드가 아래에 있습니다. 나는 각각 196,97 및 39 시트가 존중되는 세 개의 파일이 있습니다. 코드는 작동하지만 너무 오래 걸립니다.
실행 시간을 줄이는 더 나은 방법을 제안할 수 있습니까 이 링크는샘플 원본 Excel 파일입니다. 이 질문을 하기 위해 수정했습니다.
내 원래 코드는
Team3Q<‑getSheetNames("reportTeam_3_FultonCountySchools.xlsx")
#using For Loop to extract particular cells from each of the sheets in the Excel spreadsheet.
#I need to get the content of the first column and third row of each sheet.
for (j in 1:length(Team3Q)){
tmp<‑read.xlsx("reportTeam_3_FultonCountySchools.xlsx",
sheet = j,
startRow = 3,
colNames = FALSE,
rowNames = FALSE,
detectDates = FALSE,
skipEmptyRows = TRUE,
skipEmptyCols = TRUE,
rows = c(3,4),
cols = c(1:2),
check.names = FALSE,
namedRegion = NULL,
na.strings = "NA",
fillMergedCells = FALSE
)
if (j==1) Team3Questions<‑tmp else Team3Questions<‑rbind(Team3Questions,tmp) #happend to previous
}
Team3<‑ cbind(Team3QNumber,Team3Questions)
입니다.
참조 솔루션
방법 1:
you can use lapply() instead. This will give you a list, with one item per sheet. Then rbind the list items together with do.call():
Team3list <‑ lapply(Team3Q, function(x) read.xlsx("reportTeam_3_FultonCountySchools.xlsx",
sheet=x, #function‑x is here
startRow = 3,
colNames = FALSE,
rowNames = FALSE,
detectDates = FALSE,
skipEmptyRows = TRUE,
skipEmptyCols = TRUE,
rows = c(3,4),
cols = c(1:2),
check.names = FALSE,
namedRegion = NULL,
na.strings = "NA",
fillMergedCells = FALSE)
)
Team3 <‑ do.call(rbind, Team3list)
edit: I just realized that if you use sapply instead of lapply, you will get these 3.2.1, 3.2.2, ... values instead of 1,2,3,4,... You only need to gsub() them afterwards to get rid of this ".X1" at the end.
Team3list1 <‑ sapply(...)
Team3 <‑ do.call(rbind, Team3list1)
rownames(Team3) <‑ rownames(gsub(".X1$","", Team3))
(by Lilian Tan、NicolasH2)