其中一些似乎过于复杂,这里有一个简单的方法,使用样本将任何数据集分成 3 个,甚至是任意数量的集合。
# Simple into 3 sets.
idx <- sample(seq(1, 3), size = nrow(iris), replace = TRUE, prob = c(.8, .2, .2))
train <- iris[idx == 1,]
test <- iris[idx == 2,]
cal <- iris[idx == 3,]
如果您更喜欢可重用代码:
# Or a function to split into arbitrary number of sets
test_split <- function(df, cuts, prob, ...)
{
idx <- sample(seq(1, cuts), size = nrow(df), replace = TRUE, prob = prob, ...)
z = list()
for (i in 1:cuts)
z[[i]] <- df[idx == i,]
z
}
z <- test_split(iris, 4, c(0.7, .1, .1, .1))
train <- z[1]
test <- z[2]
cal <- z[3]
other <- z[4]