R中逻辑回归建模中的子集

问题描述

我在 R 中的逻辑回归过程中拆分和子集我的数据时收到以下错误消息。我卡在“子集”步骤。

    library(caTools)
    split <-sample.split(df1,SplitRatio = 0.5)
    split
    training <- subset(df1,split == "TRUE")
    testing <- subset(df1,split == "FALSE")

错误

错误:必须使用有效的下标向量对行进行子集。逻辑 下标必须与索引输入的大小匹配。 x 输入有大小 333030 但下标 i 的大小为 9。运行 rlang::last_error() 以查看 发生错误的地方。

解决方法

您正在拆分列。如果您阅读帮助页面:

用法:

  sample.split( Y,SplitRatio = 2/3,group = NULL )
  Arguments:

   Y: Vector of data labels. If there are only a few labels (as is
      expected) than relative ratio of data in both subsets will be
      the same.

您正在提供整个数据框,它作为一个列表读取。因此,如果您有一个因变量,例如 y ,它将是:

split <-sample.split(df1$y,SplitRatio = 0.5)
training <- df1[split,]
testing <- df1[!split,]

split <-sample.split(1:nrow(df1),]