Caret - 基于多个变量创建分层数据集

Fal*_*lco 2 r r-caret

在 R 包 caret 中,我们是否可以使用函数 createDataPartition()(或 createFolds() 进行交叉验证)基于多个变量创建分层训练和测试集?

以下是一个变量的示例:

#2/3rds for training
library(caret)
inTrain = createDataPartition(df$yourFactor, p = 2/3, list = FALSE)
dfTrain=df[inTrain,]
dfTest=df[-inTrain,]
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,训练集和测试集按“df$yourFactor”分层。但是是否可以使用多个变量(例如“df$yourFactor”和“df$yourFactor2”)进行分层?以下代码似乎有效,但我不知道它是否正确:

inTrain = createDataPartition(df$yourFactor, df$yourFactor2, p = 2/3, list = FALSE)
Run Code Online (Sandbox Code Playgroud)

小智 8

如果您使用tidyverse.

例如:

df <- df %>%
  mutate(n = row_number()) %>% #create row number if you dont have one
  select(n, everything()) # put 'n' at the front of the dataset
train <- df %>%
  group_by(var1, var2) %>% #any number of variables you wish to partition by proportionally
  sample_frac(.7) # '.7' is the proportion of the original df you wish to sample
test <- anti_join(df, train) # creates test dataframe with those observations not in 'train.'
Run Code Online (Sandbox Code Playgroud)