如何仅通过在R编程中指定测试集来获得训练集?

时间:2018-10-27 17:48:11

标签: r sample

testpc <- 0.10
test <- sample_frac(Boston, testpc)

我想获得train而不必这样做:

trainpc <- 0.90
train <- sample_frac(Boston, trainpc)

我尝试了Boston[-test],但给出了错误。

帮助!!!!

1 个答案:

答案 0 :(得分:1)

# Using dplyr::sample_frac as implied in the question
library(MASS)
library(dplyr)
testpc <- 0.10
test <- sample_frac(Boston, testpc)
train <- Boston[!(rownames(Boston) %in% rownames(test)),]

# Wihtout using dplyr
library(MASS)
testpc <- 0.10 * nrow(Boston)
intest <- sample(1:nrow(Boston), testpc)
test <- Boston[intest,]
train <- Boston[-intest,]