【问题标题】:how to create list of test and train data frame from list of data frame如何从数据框列表创建测试和训练数据框列表
【发布时间】:2015-12-08 05:33:16
【问题描述】:

我正在尝试从列表中的多个数据帧创建多个测试和训练数据集。因此,我得到这个“1:nrow(df)中的错误:长度为0的参数”并且不明白如何解决它。我已经手动更新了没有 for 循环的列表,它工作正常。但由于某种原因,当我尝试使用 for 循环重复此过程时,我得到了错误。

我首先从 iris 数据集中创建了一个 3 三个迷你数据帧

x <- 3;
# split the data into 3 mini data frames
set.seed(1)
df_list<- split( as.data.frame(iris), sample(x,nrow(iris),replace=TRUE))

比一个空列表

TTdf_list <- list()

比一个需要** df_list**的函数;然后从 df_list 中的每个数据帧创建一个测试和训练。完成后,它会将其存储回 TTdf_list

# splitdf function will return a list of training and testing sets

splitdf <- function(dataframe) {

 for(i in 1:length(df_list)){

df <-  df_list$'i'

# creating the logic to divide the df, train(0.70) & test (0.3)
#ind <- sample(2, nrow(df), replace = TRUE, prob =c(0.7,0.3))

#Sample Indexes
indexes <- sample(1:nrow(df), size=0.3*nrow(df))

# Split data
test = df[indexes,]

train = df[-indexes,]

TTdf_list $'i' <- list(train,test)

 }
 return(TTdf_list);
}



 df_list<-lapply(RDD_df, splitdf)

比你

【问题讨论】:

  • df_list$'i' 无法按预期工作。使用[[
  • 感谢 akrun 但 df_list 正在重新调整 3 个列表,每个列表有 6 个成员?但我只想要 3 个列表,其中包含 2 个列表,即原始数据帧分为测试和训练,这个过程适用于所有这些。谢谢

标签: r


【解决方案1】:

这只是比你正在做的简单一点,虽然非常相似。

# list of three data.frames
set.seed(1)    # for reproducibble example
lst    <- split(iris, sample(3,nrow(iris),replace=TRUE))

# list of three lists, each containing a train and test df with *approx* 70/30 split
get.TT <- function(df) setNames(split(df, sample(2,nrow(df),replace=TRUE,p=c(0.7,0.3))),
                                c("train","test"))
TTlst  <- lapply(lst, get.TT)
sapply(TTlst, function(ll) sapply(ll, nrow))
#        1  2  3
# train 27 44 40
# test  15 16  8

请注意,sample(..., p=...) 将返回一个样本,其比例大约p 中的比例。如果您正是需要这些比例,请使用:

# list of three lists, each containing a train and test set with *exactly* 70/30 split
get.TT <- function(df) setNames(split(df, (1:nrow(df)) %in% sample(nrow(df),0.3*nrow(df))),
                                c("train","test"))
TTlst  <- lapply(lst, get.TT)
sapply(TTlst, function(ll) sapply(ll, nrow))
#        1  2  3
# train 30 42 34
# test  12 18 14

关于你的代码为什么不能工作(除了使用不正确的语法):你的函数接受和参数dataframe,但你从不使用它。

【讨论】:

  • 感谢吉尔霍华德; setNames() 在这里做什么?如果你不介意我问。我刚刚意识到通过使用 for 循环而不是拆分,我让自己的生活变得艰难。再次感谢
  • setnames(...) 设置对象的名称并返回命名对象。这是names(obj) &lt;- c("train","test")的快捷方式
  • 再次感谢。这是尝试在 DF 上执行此类操作时的最佳做法吗?
猜你喜欢
  • 2021-07-19
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2016-02-29
相关资源
最近更新 更多