将数据集分成60%,20%,20%。

4
我正在尝试按照以上问题所述,从2组数据转移到3组数据。以下是我使用的脚本:
set.seed(125)
d <- sample(x = nrow(db), size = nrow(db) * 0.60, )
train60 <-db[d, ]
valid40 <-db[-d, ]

有没有办法修改上面的脚本?我尝试创建了另一行:valid40 <- db[-d] * 0.2,但是没有起作用。

当前数据集有几个因素变量。

我尝试在cut函数上使用Frank的解决方案,但是我总是得到以下错误:

Error in cut.default(seq(nrow(df)), nrow(df) * cumsum(c(0, spec)), labels = names(spec)) : lengths of 'breaks' and 'labels' differ

即使在网上寻求帮助后,我仍然不理解这个错误。


样本50%的valid40是多少?.. 取样(valid40,nrow(valid40)/2)。 - r.user.05apr
也许还可以参考 modelr::crossv_mc - Axeman
2个回答

5
如果我理解你的意思正确,那么你想要对样本进行60%、20%和20%的无重复分叉。我以鸢尾花数据为例,其中包含150行和5列。
samp <- sample(1:nrow(iris),.6*nrow(iris)) ##60 and 40 bifurcation

train60 <- iris[samp,] ## This is the 60% chunk
remain40 <- iris[-samp,]  ## This is used for further bifurcation

samp2 <- sample(1:nrow(remain40),.5*nrow(remain40))

first20 <- remain40[samp2,] ## First chunk of 20%
secnd20 <- remain40[-samp2,] ## Second Chunk of 20%

Reduce("intersect",list(train60,first20,secnd20)) ##Check to find if there is any intersect , 0 rows means everything is fine and sample are not repetitive.

@halfer:关于在问题中添加“紧急”的道歉。 - user149635
嗨Jeppe和Pkr:非常感谢您回答我的“求救”电话,并提供了详细的解释,对于新手来说非常有帮助。这两个脚本都运行得非常好!我想投票支持你们的回答,但不确定系统是否允许。 - user149635

2
db <- data.frame(x=1:10, y=11:20)

set.seed(125)
d <- sample(x=nrow(db),size=nrow(db)*0.60,)

train60 <-db[d,]

valid40 <-db[-d,]

现在,在每个新数据框中只取valid40的一半:
e <- sample(x=nrow(valid40),size=nrow(valid40)*0.50,)

train20 <-valid40[e,]
valid20 <- valid40[-e,]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接