# Converting R variables to sage

If I have a bunch of notebook cells with R code using the %r method, is there an easy way to grab the data as a varible in Python/Sage without converting the whole thing to use r.command syntax?

edit retag close merge delete

Sort by ยป oldest newest most voted

Victory! I knew this should be possible.

In the notebook:

%r
a <- c(1,2,3)
a

[1] 1 2 3

from sage.interfaces.r import RElement
b = RElement(r,'a')
c = b._sage_()
c

[1, 2, 3]


and then you can do stuff to c because it's not an RElement.

c[1] = 3
c

[1, 3, 3]


I don't know whether this is worth wrapping slightly better, or if that is even possible. But hopefully this works for you!

more

Note this will only work with data that actually converts nicely into Sage/Python structures. For instance, I don't know whether data frames convert nicely into arrays or something.

( 2011-10-14 16:34:33 -0600 )edit

If you've done

%r
a <- c(1,2,3)


in one notebook cell. You can just do

r('a')._sage_()


to get back the list [1, 2, 3]. This is a bit easier than using RElement.

more

Hah, do I look silly now! Can you think of any even simpler syntax that would be consistent with the rest of Sage? At the very least we should document this notebook behavior clearly in r?.

( 2011-11-11 15:35:44 -0600 )edit

You at least have access to them, though only in printed format. Here's a typical example from the worksheet (go to "Edit" to see this, but it looks fine in the notebook).

{{{id=51|
%r
a <- c(1,2,3)
///
}}}

{{{id=52|
%r
a
///
[1] 1 2 3
}}}

{{{id=58|
r.get('a')
///
'[1] 1 2 3'
}}}


I have a feeling there is another way to do this, though. The key is using _getitem_ but for RElements instead. I haven't quite nailed it down, and I have to go now, but this may be possible.

more

Probably the easiest way is to write the data out to a file in the R cell and read it in using python in a Sage cell. Make sure to write it out to the DATA directory, which you can find by doing "print DATA" in a Sage cell.

more

hmm.. I was hoping for a more direct variable conversion, but that will work. Thank you!

( 2011-10-14 05:20:25 -0600 )edit