【问题标题】:Splitting a list of data frames into multiple training and testing sets in R将数据帧列表拆分为 R 中的多个训练和测试集
【发布时间】:2022-01-11 13:27:45
【问题描述】:

我有一个数据框列表:

df1 <- data.frame(a = 1:4, b = 3:6)
df2 <- data.frame(a = c(5,3,4,4), b = c(9,9,1,0))
df_list <- list(df1, df2)

我想创建一个包含 df1_testing、df1_training、df2_testing 和 df2_training 数据集的新列表,训练集和测试集之间的比例为 75-25。

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    你可以这样做。您还可以更改函数以将拆分概率(此处为 0.75)作为参数。

    split2 <- function(df){
      sample <- sample(x = 1:nrow(df), size = floor(.75*nrow(df)), replace = F)
      list(test = df[sample,], train = df[-sample,])
    }
    lapply(df_list, split2)
    

    这给出了:

    [[1]]
    [[1]]$test
      a b
    1 1 3
    3 3 5
    2 2 4
    
    [[1]]$train
      a b
    4 4 6
    
    
    [[2]]
    [[2]]$test
      a b
    1 5 9
    2 3 9
    3 4 1
    
    [[2]]$train
      a b
    4 4 0
    

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 2018-10-13
      • 1970-01-01
      • 2017-12-25
      • 2018-11-19
      • 2018-04-22
      • 1970-01-01
      • 2018-07-21
      • 2019-05-01
      相关资源
      最近更新 更多