在R包插入符号中,我们可以使用函数createDataPartition() (或用于交叉验证的createFolds() )基于几个变量创建分层的训练和测试集吗?
下面是一个变量的示例:
#2/3rds for training
library(caret)
inTrain = createDataPartition(df$yourFactor, p = 2/3, list = FALSE)
dfTrain=df[inTrain,]
dfTest=df[-inTrain,]在上面的代码中,训练和测试集是通过'df$yourFactor‘分层的。但是可以使用几个变量(例如'df$yourFactor‘和'df$yourFactor2')进行分层吗?下面的代码似乎可以工作,但我不知道它是否正确:
inTrain = createDataPartition(df$yourFactor, df$yourFactor2, p = 2/3, list = FALSE)发布于 2019-03-23 22:20:33
如果您使用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.'发布于 2019-02-07 14:31:35
有一种更好的方法可以做到这一点。
set.seed(1)
n <- 1e4
d <- data.frame(yourFactor = sample(1:5,n,TRUE),
yourFactor2 = rbinom(n,1,.5),
yourFactor3 = rbinom(n,1,.7))地层指示器
d$group <- interaction(d[, c('yourFactor', 'yourFactor2')])样本选择
indices <- tapply(1:nrow(d), d$group, sample, 30 )获取子样本
subsampd <- d[unlist(indices, use.names = FALSE), ]这样做是在yourFactor和yourFactor2的每个组合上生成一个大小为30的随机分层样本。
https://stackoverflow.com/questions/54566428
复制相似问题