gpt4 book ai didi

r - 在 R 中将数据帧拆分为训练集和测试集

转载 作者:行者123 更新时间:2023-12-03 08:00:02 26 4
gpt4 key购买 nike

我有以下数据框:

>str(customerduration_data)

Classes 'tbl_df', 'tbl' and 'data.frame': 4495 obs. of 4 variables:

$ monthofgateOUT : Ord.factor w/ 4 levels "8"<"9"<"10"<"11": 1 1 1 1 1 1 1 1 1 1 ...

$ dayofgateOUT : Ord.factor w/ 7 levels "Monday"<"Tuesday"<..: 4 5 1 1 1 1 1 2 2 3 ...

$ timeofgateOUT : Ord.factor w/ 20 levels "3"<"4"<"5"<"6"<..: 13 4 2 3 3 11 15 10 13 14 ...

$ durationCUST_hours: num 95.63 5.73 10.73 10.2 14.4 .

我想使用以下命令将此数据拆分为训练集和测试集:

install.packages("caTools")

library (caTools)

set.seed(6)

customerduration_data$spl=sample.split(customerduration_data,SplitRatio=0.7)

但是,运行上述命令后,出现以下错误:

>Error in `$<-.data.frame`(`*tmp*`, spl, value = c(TRUE, FALSE, FALSE,  : 
replacement has 4 rows, data has 4495

如何解决这个问题?

最佳答案

作为替代方案,您可以使用base R,这会产生更快的选项(根据microbenchmark为3.4倍)并且不需要额外的软件包:

df$spl <- sample(c(rep(TRUE, floor(0.7*4495)), rep(FALSE, 4495-floor(0.7*4495))), replace = F)

将其拆分为数据集:

df$spl <- sample(c(rep(TRUE, floor(0.7*4495)), rep(FALSE, 4495-floor(0.7*4495))), replace = F)
test_data <- df[df[,'spl'] %in% TRUE, ]
train_data <- df[df[,'spl'] %in% FALSE, ]

关于r - 在 R 中将数据帧拆分为训练集和测试集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com