First time here? Check out the FAQ!

Ask Your Question
4

Converting R variables to sage

asked 13 years ago

anonymous user

Anonymous

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?

Preview: (hide)

4 Answers

Sort by » oldest newest most voted
4

answered 13 years ago

kcrisman gravatar image

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!

Preview: (hide)
link

Comments

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.

kcrisman gravatar imagekcrisman ( 13 years ago )
4

answered 13 years ago

Mike Hansen gravatar image

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.

Preview: (hide)
link

Comments

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?`.

kcrisman gravatar imagekcrisman ( 13 years ago )
1

answered 13 years ago

kcrisman gravatar image

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.

Preview: (hide)
link
1

answered 13 years ago

Jason Grout gravatar image

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.

Preview: (hide)
link

Comments

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

mlanting gravatar imagemlanting ( 13 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 13 years ago

Seen: 1,043 times

Last updated: Nov 11 '11