Pass string as argument

Issue #260 invalid
Åsmund Hjulstad created an issue

Trying this:

def density(x, weight, from_x=None, to_x=None, adjust=1):
    args = OrdDict()
    args["x"] = rpy2.robjects.vectors.FloatVector(x)
    args["weights"] = rpy2.robjects.vectors.FloatVector(weight)
    args["bw"] = rpy2.robjects.vectors.StrSexpVector("SJ")
    args["from"] = 0
    args["to"] = 35
    args["adjust"] = 1
    x, y, bw, n, call, dn, hn = robjects.r.density.rcall(tuple(args.items()), rpy2.rinterface.globalenv)
    return x, y

balks at the bw specification.

RRuntimeError: Error in switch(tolower(bw), nrd0 = bw.nrd0(x), nrd = bw.nrd(x), ucv = bw.ucv(x),  : 
  EXPR must be a length 1 vector

In R, I would probably be able to specify 'SJ' as a string, but I cannot find any way to do this with rpy2.

Comments (4)

  1. Laurent Gautier

    In R there are no scalars: "strings" are vectors of type "characters" of length 1.

    What is happening here is that in Python strings are sequences:

    >>> x = "SJ"
    >>> len(x)
    2
    >>> x[0]
    'S'
    

    Since the constructors for rpy2 vectors are accepting any python sequence, the outcome of

    rpy2.robjects.vectors.StrSexpVector("SJ")
    

    is the equivalent of the following R code:

    c("S", "J")
    

    The following change will create an R vector of length 1 containing the string "SJ" as its sole element:

    args["bw"] = rpy2.robjects.vectors.StrSexpVector(("SJ",))
    
  2. Log in to comment