분할-적용-결합

R에서 확장 가능한 데이터 처리

Michael Kane

Assistant Professor, Yale University

분할-적용-결합

  • 분할: split()
  • 적용: Map()
  • 결합: Reduce()
R에서 확장 가능한 데이터 처리

split()으로 분할하기

split() 함수는 데이터를 분할합니다

  • 첫 번째 인수: 분할할 벡터 또는 data.frame
  • 두 번째 인수: 파티션을 정의하는 factor 또는 integer
R에서 확장 가능한 데이터 처리
# Get the rows corresponding to each of the years in the mortgage data
 year_splits <- split(1:nrow(mort), mort[,"year"])
# year_splits is a list
class(year_splits)
"list"
# The years that we've split over
names(year_splits)
"2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015"
# The first few rows corresponding to the year 2010
year_splits[["2010"]][1:10]
1  6  7 10 21 23 24 27 29 38
R에서 확장 가능한 데이터 처리

Map()으로 계산하기

Map() 함수는 각 파티션을 처리합니다

  • 첫 번째 인수: 각 파티션에 적용할 함수
  • 두 번째 인수: 파티션
R에서 확장 가능한 데이터 처리

Map()으로 계산하기

col_missing_count <- function(mort) {
   apply(mort, 2, function(x) sum(x == 9))} 
# For each of the years count the number of missing values for 
# all columns
missing_by_year <- Map(
   function(x) col_missing_count(mort[x, ]),
   year_splits)

missing_by_year[["2008"]]
enterprise         record_number                   msa 
        0                    12                     0 
# ...
R에서 확장 가능한 데이터 처리

Reduce()로 결합하기

Reduce() 함수는 모든 파티션의 결과를 결합합니다

  • 첫 번째 인수: 결합에 사용할 함수
  • 두 번째 인수: 분할된 데이터
R에서 확장 가능한 데이터 처리
# Calculate the total missing values by column
Reduce(`+`, missing_by_year)
enterprise         record_number                   msa 
         0                    64                     0 
# ... 
# Label the rownames with the year
mby <- Reduce(rbind, missing_by_year)
row.names(mby) <- names(year_splits)
mby[1:3, 1:3]
     enterprise record_number msa
2008          0            12   0
2009          0             8   0
2010          0            10   0

R에서 확장 가능한 데이터 처리

연습해 봅시다!

R에서 확장 가능한 데이터 처리

Preparing Video For Download...