I need to run robust ANOVA from Python. The function I want to use is
t2way from R package WRS2. I tried with r2py, but I’m stuck with an error:
>>> import rpy2.robjects.packages as rpackages >>> from rpy2.robjects import pandas2ri >>> pandas2ri.activate() >>> df = pd.read_csv("https://github.com/lawrence009/dsur/raw/master/data/goggles.csv") >>> rdf = pandas2ri.py2rpy(df) >>> WRS2 = rpackages.importr('WRS2') >>> WRS2.t2way("attractiveness ~ gender*alcohol", data = rdf) RRuntimeError: Error in x[[grp[i]]] : attempt to select less than one element in get1index
I’m looking for either a way to make this work with rpy2, or (even better) a port of WRS2 to the python environment. Any help would be much appreciated.
If the issue is with columns in the dataframe that are not factors (as suggested in other answer), casting them into factors is quite easy:
rdf = pandas2ri.py2rpy(df) base = importr('base') import rpy2.robjects as ro for cn in ('alcohol', 'gender'): i = rdf.colnames.index(cn) rdf[i] = base.as_factor(rdf[i]) # We could also do it with # rdf[i] = ro.FactorVector(rdf[i])
To be on the safe side, it is recommended to create an R formula object. Some R functions will accept strings and assume that they are formula, but this is up to a package author and not always the case.
WRS2.t2way(ro.Formula('attractiveness ~ gender*alcohol'), data = rdf)