rbind 和 cbind 一起列出

rbind and cbind lists together

我有下面的代码,其中我将列表 SampleDf 和 sampleDF2 rbind 在一起,然后将两个字符向量 cbind 到它上面。我想做的是创建一个函数,我可以将另一个 sampleDF3、Recipe3 和成分列表传递给它,并将它们类似地 rbind 和 cbind 放在一起。有没有一种简单的方法可以用 lapply 或 do.call 来做到这一点?我的最终目标是能够将 sampleDF、食谱和成分的列表传递给该函数,并将它们全部 rbind 和 cbind 在一起,类似于下面的示例。

Code:
try1<-cbind(cbind(RecipeName<-c("Recipe1","Recipe2"),ingredients<-c("","Beans"))
          ,rbind(
                  SampleDf
                 ,sampleDf2

                  )
             )


Data:

dput(SampleDf)
structure(c(45.8490717149901, 75.6532220962743, 49.4757541141121, 
21.7923657299986, 153.255016847245), .Dim = c(1L, 5L), .Dimnames = list(
    "Test set", c("ME", "RMSE", "MAE", "MPE", "MAPE")))

dput(sampleDf2)
structure(c(-1.39930351254246, 65.1992541962796, 46.5664097914753, 
-364.369685854671, 412.539393211685), .Dim = c(1L, 5L), .Dimnames = list(
    "Test set", c("ME", "RMSE", "MAE", "MPE", "MAPE")))

dput(sampleDf3)
structure(c(0, 65.1992541962796, 1, 
-364.369685854671, 10), .Dim = c(1L, 5L), .Dimnames = list(
    "Test set", c("ME", "RMSE", "MAE", "MPE", "MAPE")))

您可以执行以下操作:

require(dplyr)
bind_all <- function(rows, cols){
  rows <- lapply(rows, as.data.frame)
  cols <- vapply(cols, as.data.frame, list(1))
  bind_cols(bind_rows(rows), cols)
}

bind_all(list(SampleDf, sampleDf2), 
         list(RecipeName=c("Recipe1","Recipe2"),ingredients=c("","Beans")))

这给你:

         ME     RMSE      MAE        MPE     MAPE RecipeName ingredients
1 45.849072 75.65322 49.47575   21.79237 153.2550    Recipe1            
2 -1.399304 65.19925 46.56641 -364.36969 412.5394    Recipe2       Beans