LoginSignup
1
3

More than 5 years have passed since last update.

Rのデータフレームを交差検証用にK個に分割する - cvTools編

Last updated at Posted at 2017-05-27

(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を取り出す例
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3