modLmakur modLmakur - 1 month ago 21
R Question

rbind and cbind lists together

I have the code below in which I rbind the lists SampleDf and sampleDF2 together, and then cbind two character vectors on to it. What I would like to do is create a function where I could pass it another sampleDF3, Recipe3, and list of ingredients and have them similarly rbind and cbind together. Is there a simple way to do this with like lapply or do.call? My end goal is to be able to pass the function a list of sampleDF, Recipe, and ingredients and have them all rbind and cbind together similar to the example below.

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")))

Answer

You could do the following:

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")))

Which gives you:

         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
Comments