如何从数据帧列表中创建测试列表和训练数据帧

时间:2015-09-11 15:34:59

标签: r

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

我首先从虹膜数据集

创建了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)

比你

1 个答案:

答案 0 :(得分:0)

这比你正在做的要简单一点,虽然非常相同。

cName = "Ledger Account"
cA = Sheets(1).Rows.Find(What:=UCase(cName), LookAt:=xlWhole, SearchDirection:=xlNext).Column

请注意,# 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 ,但你永远不会使用它。

相关问题