分割数据集R实现(spliting dataset)

方法一 :caTools包,sample.split函数

# Splitting the dataset into the Training set and Test set 
install.packages('caTools') 
library(caTools) 
  
set.seed(123) 
split = sample.split(dataset$Purchased, SplitRatio = 0.75) 
  
training_set = subset(dataset, split == TRUE) 
test_set = subset(dataset, split == FALSE) 

方法二:caret包,createDataPartition函数

library(caret)
Train <- createDataPartition(data$Obesity, p=0.6, list=FALSE)
training <- data[ Train, ]
testing <- data[ -Train, ]

方法三:sample函数

ind=sample(nrow(data),nrow(data)*4/5)
training<-data[ind,]
testing<-data[-ind,]

方法四:自写函数

create_train_test <- function(data, size = 0.8, train = TRUE) {
    n_row = nrow(data)
    total_row = size * n_row
    train_sample < - 1: total_row
    if (train == TRUE) {
        return (data[train_sample, ])
    } else {
        return (data[-train_sample, ])
    }
}

#Code Explanation
#function(data, size=0.8, train = TRUE): Add the arguments in the function
#n_row = nrow(data): Count number of rows in the dataset
#total_row = size*n_row: Return the nth row to construct the train set
#train_sample <- 1:total_row: Select the first row to the nth rows
#if (train ==TRUE){ } else { }: If condition sets to true, return the train set, else the test set.

 

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值