B.Gees
B.Gees

Reputation: 1155

R apply loop with return list

I tried to replace for loop by apply loop in an existant R script. Nevertheless, my old function returns multiple dataFrames list like that return(list(df1,df2)). For some details, an example is presented below :

Old Script:

MyFunction = function(input){
  df1=array(NA,c(0,1))
  df2=array(NA,c(0,1))
  for(i in 1:n){
    ...
    df1 = rbind(df1,action1(input))
    df2 = rbind(df2,action2(input))
  }
return(list(df1,df2))

New Script:

Object = do.call(rbind, lapply(1:n,function(i){
  df1 = action1(input)
  df2 = action2(input)
  return(list(df1,df2))
}))

I obtain :

      [,1]   [,2]   [,3]   [,4]   [,5]  
 [1,] List,2 List,2 List,2 List,2 List,2
 [2,] List,2 List,2 List,2 List,2 List,2
 [3,] …

I have no idea to resolve my problem. Any help would be appreciate.

Thanks in advances,

B.Gees

Upvotes: 0

Views: 1171

Answers (1)

akuiper
akuiper

Reputation: 214927

do.call(rbind, ...) is usually used for row bind a list of data frames/matrices. You have a list of list of data frames, and you want to bind them accordingly, you can try the following pattern.

Object = do.call(Map, c(f = rbind, lapply(1:n,function(i){
  df1 = action1(input)
  df2 = action2(input)
  return(list(df1,df2))
})))

do.call(Map, ...) passes all lists returned by lapply as arguments to Map which then pass all data frames from the same positions to rbind. i.e. all df1 will be bound together and all df2 will be bound together.

Upvotes: 1

Related Questions