Search code examples
pythonrpy2

calling CCF function in python


I am trying to call the ccf function used in r with python.

from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

string = """
cc <- function(x,y) {
ccf(x,y)
}
"""

powerpack = SignatureTranslatedAnonymousPackage(string, "powerpack")

Calling:

import rpy2.robjects as ro

x = [1,2,3,4,5,5]
y = [5,6,7,8,8,9]

x = ro.Vector(tuple(x))
y = ro.Vector(tuple(y))

print (powerpack.cc(x,y))

Error:

RRuntimeError: Error in x[, (1 + cs[i]):cs[i + 1]] <- xx : 
incorrect number of subscripts on matrix

Any suggestions on how to correct this would be great.


Solution

  • Try this:

    from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
    import rpy2.robjects as ro
    
    
    string = """
    cc <- function(x,y) {
    xx <- unlist(x, recursive=FALSE)
    yy <- unlist(y, recursive=FALSE)
    ccf(xx, yy)
    }
    """
    
    powerpack = SignatureTranslatedAnonymousPackage(string, "powerpack")
    
    x = [1,2,3,4,5,5]
    y = [5,6,7,8,8,9]
    
    x = ro.Vector(x)
    y = ro.Vector(y)
    
    print (powerpack.cc(x,y))
    

    Explanation:

    1. First, if you do ro.Vector(tuple(x)), you will get a different error.

    NotImplementedError: Conversion 'py2ri' not defined for objects of type ''

    At least for the my version of python (3.7.0). So this is probably not what you want.

    1. If the two variables are made into Vectors from lists and then handed over to R, they are actually lists of lists (each element being its own 1-element list). So you need to unlist() before you can apply ccf(). Note that in this case you actually do get the error you reported.