(1) cvTools パッケージの cvFolds を使って cvFolds
クラスのオブジェクトを作る:
n <- dim(df)[1] # 分割元のデータフレーム df の行数を n に代入
library(cvTools)
folds <- cvFolds(n, K = 5) # ランダム5分割の例
(2) 「どのfoldに属するかの integer vector」である which
を使って、index管理用のデータフレームを作る:
library(dplyr)
indices <- as.data.frame(list(fold = folds$which)) %>%
mutate(idx = row_number())
(3) indices
から所望のfoldでフィルタしたidxを使って df をフィルタする:
df[(indices %>% filter(fold == 4))$idx,] # 4番目のfoldを取り出す例