modLmakur modLmakur - 10 months ago 74
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 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.




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

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

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

Answer Source

You could do the following:

bind_all <- function(rows, cols){
  rows <- lapply(rows,
  cols <- vapply(cols,, list(1))
  bind_cols(bind_rows(rows), cols)

bind_all(list(SampleDf, sampleDf2), 

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