Passing a list of randomForest objects back to R with rpy2
Question: I am trying to combine a number of random forest models using rpy2. The
`combine` command in R looks fairly straight forward but I am not sure how to
pass the RF objects from python to R.

Simple example:

    
    
    import pandas as pd
    import numpy as np
    import sys
    if sys.version_info[0] < 3:
        from string import lowercase
    else:
        from string import ascii_lowercase as lowercase
    import rpy2.robjects as robjects
    from rpy2.robjects import pandas2ri
    pandas2ri.activate()
    r = robjects.r
    
    r.library("randomForest")
    
    df = pd.DataFrame(data=np.random.random(size=(100, 10)), columns=[a for a in lowercase[:10]])
    cols = df.columns
    RF = []
    
    for _ in range(5):
        df['train'] = np.random.random(size=100) < .75
        rf = r.randomForest(robjects.Formula('a~.'), data=df[df.train][cols])
        RF.append(rf)
    

When I try and `combine` RF models in R

    
    
    RFall = r.combine(RF)
    

Returns the error:

    
    
    Error in (function (...)  : 
      Argument must be a list of randomForest objects
    

I have looked at other functions in `robjects` but can't find the one that
will do it.


Answer: The error message is originating from R, there the list expected is an R list.

Try using:

    
    
    RFl = robjects.vectors.ListVector([('X%i' % i, x) for i, x in enumerate(RF)])
    

**edit:** the constructor for ListVector wants names for the list elements

** 2nd edit:** However, the real path to a solution is to notice that you were
not calling `combine()` correctly and the error message returned when calling
`combine()` is quite misleading. What you want(ed) is

    
    
    RFall = r.combine(*RF)
    

