分割・適用・結合

Rで学ぶスケーラブルなデータ処理

Michael Kane

Assistant Professor, Yale University

分割・適用・結合

  • 分割:split()
  • 適用:Map()
  • 結合:Reduce()
Rで学ぶスケーラブルなデータ処理

split() によるパーティション分割

split() 関数はデータを分割します

  • 第1引数:分割するベクターまたは data.frame
  • 第2引数:パーティションを定義する 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() 関数はパーティションを処理します

  • 第1引数:各パーティションに適用する関数
  • 第2引数:パーティション
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() 関数はすべてのパーティションの結果を結合します

  • 第1引数:結合に使用する関数
  • 第2引数:分割されたデータ
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...