py.call: Calls Python functions and methods from R

Description Usage Arguments Value Examples

Description

This function runs a Python function taking as arguments R objects and returning an R object. Some limitations exist as to the nature of the objects that can be passed between R and Python, mainly which data types can be converted to/from JSON in R (using jsonlite) and Python (using the json module).

Usage

1
2
3
py.call(fname, ..., json.opt.args = getOption("SnakeCharmR.json.opt.args",
  list(auto_unbox = TRUE, null = "null")),
  json.opt.ret = getOption("SnakeCharmR.json.opt.ret", list()))

Arguments

fname

name of function/method to call

...

R objects to pass as arguments to the Python function or method

json.opt.args

explicit arguments to pass to jsonlite::toJSON when serializing the function argument values

json.opt.ret

explicit arguments to pass to jsonlite::fromJSON when deserializing the function return value

Value

an R object containing the function or method call return value after serialization to JSON in the Python environment and deserialization from JSON in the R environment

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
py.call("len", 1:3)
# [1] 3

py.call("repr", 1:3)
# [1] "[1, 2, 3]"

a <- 1:4
b <- 5:8
py.exec("def concat(a,b): return a+b")
py.call("concat", a, b)
# [1] 1 2 3 4 5 6 7 8

py.assign("a",  "hola hola")
py.call("a.split", " ")
# [1] "hola" "hola"

# by default jsonlite::toJSON is called on the function call arguments
# with auto_unbox = TRUE, so vectors of length 1 are simplified to
# scalar values in Python
py.call("repr", "foo bar")
# [1] "u'foo bar'"

# if we explicitly set auto_unbox to FALSE, a vector of length 1
# becomes a Python list of length 1
py.call("repr", "foo bar", json.opt.args = list(auto_unbox = FALSE))
# [1] "[u'foo bar']"

Example output

SnakeCharmR 1.0.7.1 - R and Python Integration
Contribute and submit issues at https://github.com/asieira/SnakeCharmR

Python version 2.7.6 (default, Nov 13 2018, 12:50:15) 
[GCC 4.8.4]
[1] 3
[1] "[1, 2, 3]"
[1] 1 2 3 4 5 6 7 8
[1] "hola" "hola"
[1] "u'foo bar'"
[1] "[u'foo bar']"

SnakeCharmR documentation built on May 2, 2019, 6:21 a.m.