programing

여러 개의 (excel) 파일을 R로 읽으려면 어떻게 해야 합니까?

fastcode 2023. 4. 10. 22:16
반응형

여러 개의 (excel) 파일을 R로 읽으려면 어떻게 해야 합니까?

R에 로드하는 중간 크기의 Excel 파일(약 100열 5000~50.0000 행)이 수백 개 있습니다.이름 짓기 패턴이 뚜렷해요x_1.xlsx,x_2.xlsx,기타.

이 파일을 가장 빠르고 간단한 방법으로 R에 로드하려면 어떻게 해야 합니까?

와 함께list.files작업 디렉토리에 있는 모든 파일 이름 목록을 만들 수 있습니다.다음에 사용할 수 있습니다.lapply목록을 루프하여 각 파일을 읽습니다.read_excel에서 기능하다readxl패키지:

library(readxl)
file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)

이 방법은 코스 외에서도 다음과 같은 다른 파일 읽기 기능과 함께 사용할 수 있습니다.read.csv또는read.table교환만 하면 됩니다.read_excel적절한 파일 읽기 기능을 사용하여 에서 올바른 패턴을 사용하고 있는지 확인합니다.list.files.

하위 디렉터리에 파일을 포함하려면 다음을 사용하십시오.

file.list <- list.files(pattern='*.xlsx', recursive = TRUE)

기타 Excel 파일 읽기 패키지: openxlsxxlsx


각 파일에 대해 열이 동일하다고 가정할 경우 각 파일을 사용하여 하나의 데이터 프레임에 바인드할 수 있습니다.bind_rows에서:

library(dplyr)
df <- bind_rows(df.list, .id = "id")

또는 을 사용하여rbindlistfrom :

library(data.table)
df <- rbindlist(df.list, idcol = "id")

둘 다 A를 추가할 수 있는 옵션이 있습니다.id개별 데이터 집합을 식별하기 위한 열입니다.


업데이트: 숫자 식별자를 원하지 않는 경우 다음을 사용하십시오.sapply와 함께simplify = FALSE파일을 읽다file.list:

df.list <- sapply(file.list, read.csv, simplify=FALSE)

사용시bind_rows 또는rbindlistid이제 열에는 파일 이름이 포함됩니다.

또 다른 접근법으로서purrr-표준:

library(purrr)
file.list <- list.files(pattern='*.csv')
file.list <- setNames(file.list, file.list) # only needed when you need an id-column with the file-names

df <- map_df(file.list, read.csv, .id = "id")

이름 있는 목록을 얻기 위한 다른 방법:숫자 식별자만 원하지 않는 경우 파일 이름을 바인딩하기 전에 목록의 데이터 프레임에 할당할 수 있습니다.여기에는 몇 가지 방법이 있습니다.

# with the 'attr' function from base R
attr(df.list, "names") <- file.list
# with the 'names' function from base R
names(df.list) <- file.list
# with the 'setattr' function from the 'data.table' package
setattr(df.list, "names", file.list)

이제 데이터 프레임 목록을 하나의 데이터 프레임에 바인딩할 수 있습니다.rbindlistdata.table 또는bind_rowsdplyr에서.id이제 열에는 숫자 식별자 대신 파일 이름이 포함됩니다.

언급URL : https://stackoverflow.com/questions/32888757/how-can-i-read-multiple-excel-files-into-r

반응형