I am running a simple R script in python using the following code.
import rpy2.robjects as robjects
r=robjects.r
output = r.source("sample.R")
Now when I print the output
print (output)
I am getting script's last variable only as an output and not all the variable (which I was not expecting. Also I was thinking if I call c or data, the results will be printed as such but python isn't identifying these variables coded in R). I am not sure how to call all these variables.
I am writing very simple code in R script just for testing. My R script looks like:
a <- 1
b <- 3
c <- a + b
data = 1:20
now on calling the script and printing the results I am getting these the following at output. I am not sure what's happening.
$value
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$visible
[1] FALSE
I am not sure how to exactly print variable as it is from R to python. Please guide me to it. Your help will be appreciated.
Regards
Your variable output will only store the output from the source file, which is exactly what you get, id est the last variable. But all the variables actually live somewhere, in an R environment, which you can get with robjects.globalenv.
Knowing that you can easily retrieve the value for each variable that you created in R:
import rpy2.robjects as robjects
robjects.r.source("sample.R")
print(robjects.globalenv["a"])
print(robjects.globalenv["b"])
print(robjects.globalenv["c"])
print(robjects.globalenv["data"])
Related
Is there a way/plug-in to enable output without "print()" in SublimeText?
For example,
a = 1 + 2
print (a)
Output:
3
Wanted:
a = 1 + 2
a
Output:
3
P.s. I also tried below:
I am pretty sure that the answer is no. You can rename the print function to make it less noticable like this:
_ = print
a = 2
_(a)
Output is 2
Alternatively:
As a few people mentioned in the comments, what you are likely looking for is a repl, which you can get by simply running python command directly in your terminal.
like this:
$ python
that should take you to an interactive environment that gives you real time results for the python code you input. Below is an example...
>>> a = 1 + 2
>>> a
3
>>> a + 25
28
>>> a
3
>>> a = a + 25
>>> a
28
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate. I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)
For example:
>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>
You could use iterate or iter_next.
As an example, consider a python generator firstn.py:
def firstn(n):
num = 0
while num < n:
yield num
num += 1
You can traverse the generator either with iterate :
library(reticulate)
source_python('firstn.py')
gen <- firstn(10)
gen
#<generator object firstn at 0x0000020CE536AF10>
result <- iterate(gen)
result
# [1] 0 1 2 3 4 5 6 7 8 9
or with iter_next:
iter_next(gen)
[1] 0
iter_next(gen)
[1] 1
iter_next(gen)
[1] 2
I'm not sure if you can in R directly, but you definitely can in R Markdown. I use R Markdown to flip objects back and forth between the two.
I use a basic html_document YAML output. However, I don't typically knit this type of RMD, so I don't think it really matters what you put there if you use it the same way.
When you use reticulate you need an environment.
So first I'll have an R chunk:
```{r setup}
library(tidyverse) # for random r object creation to use in Python
library(reticulate)
use_virtualenv("KerasEnv") # this is an environment I already have setup
# creating R objects to use with Python
str(diamonds)
cut <- diamonds$cut %>% unique()
```
Then I'll create my Python chunk.
```{r usingPy,results="asis",engine="python"}
import numpy as np
import random
diamonds_py = r.diamonds # bring dataset into Python
mxX = max(diamonds_py.x) # create a new Python object to bring into R
print(mxX)
# 10.74
cut_py = r.cut # bring vector into Python
```
Now let's say I want to bring something from Python back into R.
```{r tellMeMore}
# bring Python object into R
mxX_r = py $ mxX
# [1] 10.74
```
You can run the Python and R code line by line, by chunk, or knit. To clear the Python environment, I'm pretty sure you have to restart RStudio.
I am currently working on a code to find a value C which I will then compare against other parameters. However, whenever I try to run my code I receive this error: ValueError: math domain error. I am unsure why I am receiving this error, though I think it's how I setup my equation. Maybe there is a better way to write it. This is my code:
import os
import math
path = "C:\Users\Documents\Research_Papers"
uH2 =5
uHe = 3
eH2 = 2
eHe = 6
R = ((uH2*eH2)/(uHe*eHe))
kH2=[]
kHe=[]
print(os.getcwd()) # see where you are
os.chdir(path) # use a raw string so the backslashes are ok
print(os.getcwd()) # convince yourself that you're in the right place
print(os.listdir(path)) # make sure the file is in here
myfile=open("hcl#hfs.dat.txt","r")
lines=myfile.readlines()
for x in lines:
kH2.append(x.split(' ')[1])
kHe.append(x.split(' ')[0])
myfile.close()
print kH2
print kHe
g = len(kH2)
f = len(kHe)
print g
print f
for n in range(0,7):
C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
print C
It then returns this line saying that there is a domain error.
C = (((math.log(float(kH2[n]),10)))-(math.log(float(kHe[n]),10)))/math.log(R,10)
ValueError: math domain error
Also, for the text file, I am just using a random list of 6 numbers for now as I am trying to get my code working before I put the real list of numbers in. The numbers I am using are:
5 10 4 2
6 20 1 2
7 30 4 2
8 40 3 2
9 23 1 2
4 13 6 2
Try to check if the value inside the log is positive as non-positive value to a log function is a domain error.
Hope this helps.
I have the following R script called Test.R:
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(2,4,6,8,10,12,14,16,18,20)
plot(x,y, type="o")
x
y
I am running it via Python using this Python script called Test.py:
import subprocess
proc = subprocess.Popen(['Path/To/Rscript.exe',
'Path/To/Test.R'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print stdout
# Alternative Code to see output
# retcode = subprocess.call(['Path/To/Rscript.exe',
# 'Path/To/Test.R'])
When I run the python script Test.py, I get the following output in Pycharm:
[1] 1 2 3 4 5 6 7 8 9 10
[1] 2 4 6 8 10 12 14 16 18 20
So the usual text results show up fine, but how do I get the plots to show? I've tried changing the file from Rscript.txt to Rgui.exe but I get the following error and it only opens up Rgui:
ARGUMENT Path/To/Test.R __ignored__
is there an easy way for the output to display? I know this is a simple problem but I'm wondering how this will extend to other plot commands in R like acf() or pacf(). Should I use ggplot2 to save he plots and just tell Python to open the saved files?
Thanks.
Add:
show()
after:
plot(x,y, type="o")
i am using rpy2-2.0.7 (i need this to work with windows 7, and compiling the binaries for the newer rpy2 versions is a mess) to push a two-column dataframe into r, create a few layers in ggplot2, and output the image into a <.png>.
i have wasted countless hours fidgeting around with the syntax; i did manage to output the files i needed at one point, but (stupidly) did not notice and continued fidgeting around with my code ...
i would sincerely appreciate any help; below is a (trivial) example for demonstration. Thank you very much for your help!!! ~ Eric Butter
import rpy2.robjects as rob
from rpy2.robjects import r
import rpy2.rlike.container as rlc
from array import array
r.library("grDevices") # import r graphics package with rpy2
r.library("lattice")
r.library("ggplot2")
r.library("reshape")
picpath = 'foo.png'
d1 = ["cat","dog","mouse"]
d2 = array('f',[1.0,2.0,3.0])
nums = rob.RVector(d2)
name = rob.StrVector(d1)
tl = rlc.TaggedList([nums, name], tags = ('nums', 'name'))
dataf = rob.RDataFrame(tl)
## r['png'](file=picpath, width=300, height=300)
## r['ggplot'](data=dataf)+r['aes_string'](x='nums')+r['geom_bar'](fill='name')+r['stat_bin'](binwidth=0.1)
r['ggplot'](data=dataf)
r['aes_string'](x='nums')
r['geom_bar'](fill='name')
r['stat_bin'](binwidth=0.1)
r['ggsave']()
## r['dev.off']()
*The output is just a blank image (181 b).
here are a couple common errors R itself throws as I fiddle around in ggplot2:
r['png'](file=picpath, width=300, height=300)
r['ggplot']()
r['layer'](dataf, x=nums, fill=name, geom="bar")
r['geom_histogram']()
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()
*RRuntimeError: Error: No layers in plot
r['png'](file=picpath, width=300, height=300)
r['ggplot'](data=dataf)
r['aes'](geom="bar")
r['geom_bar'](x=nums, fill=name)
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()
*RRuntimeError: Error: When setting aesthetics, they may only take one value. Problems: fill,x
I use rpy2 solely through Nathaniel Smith's brilliant little module called rnumpy (see the "API" link at the rnumpy home page). With this you can do:
from rnumpy import *
r.library("ggplot2")
picpath = 'foo.png'
name = ["cat","dog","mouse"]
nums = [1.0,2.0,3.0]
r["dataf"] = r.data_frame(name=name, nums=nums)
r("p <- ggplot(dataf, aes(name, nums, fill=name)) + geom_bar(stat='identity')")
r.ggsave(picpath)
(I'm guessing a little about how you want the plot to look, but you get the idea.)
Another great convenience is entering "R mode" from Python with the ipy_rnumpy module. (See the "IPython integration" link at the rnumpy home page).
For complicated stuff, I usually prototype in R until I have the plotting commands worked out. Error reporting in rpy2 or rnumpy can get quite messy.
For instance, the result of an assignment (or other computation) is sometimes printed even when it should be invisible. This is annoying e.g. when assigning to large data frames. A quick workaround is to end the offending line with a trailing statement that evaluates to something short. For instance:
In [59] R> long <- 1:20
Out[59] R>
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
[19] 19 20
In [60] R> long <- 1:100; 0
Out[60] R> [1] 0
(To silence some recurrent warnings in rnumpy, I've edited rnumpy.py to add 'from warnings import warn' and replace 'print "error in process_revents: ignored"' with 'warn("error in process_revents: ignored")'. That way, I only see the warning once per session.)
You have to engage the dev() before you shut it off, which means that you have to print() (like JD guesses above) prior to throwing dev.off().
from rpy2 import robjects
r = robjects.r
r.library("ggplot2")
robjects.r('p = ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()')
r.ggsave('/stackBar.jpeg')
robjects.r('print(p)')
r['dev.off']()
To make it slightly more easy when you have to draw more complex plots:
from rpy2 import robjects
from rpy2.robjects.packages import importr
import rpy2.robjects.lib.ggplot2 as ggplot2
r = robjects.r
grdevices = importr('grDevices')
p = r('''
library(ggplot2)
p <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
p <- p + opts(title = "{0}")
# add more R code if necessary e.g. p <- p + layer(..)
p'''.format("stackbar"))
# you can use format to transfer variables into R
# use var.r_repr() in case it involves a robject like a vector or data.frame
p.plot()
# grdevices.dev_off()