In rpy2, I noticed that a StrVector is factorised once it's put into a DataFrame. An example is the following.
import rpy2.robjects as ro
series_1 = ("0", "0", "0", "0")
series_1_robject = ro.StrVector(series_1) # => ['0', '0', '0', '0']
df = ro.DataFrame({"series_1": series_1_robject}) # => FactorVector [1, 1, 1, 1]
And...
>>> df[0][1]
1
It appears that when I build a DataFrame, my nice StrVector gets factorised, so 0 corresponds to factor value 1 (being R is 1-indexed), and so on. But how would I stop this from happening? It's pretty essential for me that when the input vector (series_1) is 0,0,0...,0, its representation in the resulting DataFrame will be 0, not 1. So far, I have not really been able to find anything on this matter in the documentation....
As per the note here, you can prevent this conversion to FactorVector by wrapping the StrVector with a call to ro.r.I() (the "as-is" function in R):
In [1]: import rpy2.robjects as ro
In [2]: series_1 = ("0", "0", "0", "0")
In [3]: series_1_robject = ro.StrVector(series_1)
In [4]: df = ro.DataFrame({"series_1": series_1_robject})
In [5]: df.rx2("series_1")
Out[5]:
R object with classes: ('factor',) mapped to:
<FactorVector - Python:0x113a39368 / R:0x7f8d15882e40>
[ 1, 1, 1, 1]
In [6]: df = ro.DataFrame({"series_1": ro.r.I(series_1_robject)})
In [7]: df.rx2("series_1")
Out[7]:
R object with classes: ('AsIs',) mapped to:
<StrVector - Python:0x113a398c0 / R:0x7f8d13a8aec8>
[str, str, str, str]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With