py.assign: Assign values to Python variables from R

Description Usage Arguments Examples

View source: R/py.assign.R

Description

py.assign assigns values to variables in Python. Objects are serialized as JSON strings on R with jsonlite::toJSON, are transferred to Python and are converted back to a Python value using json.loads.

Usage

1
2
3
py.assign(var.name, value,
  json.opt.args = getOption("SnakeCharmR.json.opt.args", list(auto_unbox
  = TRUE, null = "null")))

Arguments

var.name

a character string containing a valid Python variable name

value

an R object whose equivalent wants to be assigned to the variable in Python

json.opt.args

explicit arguments to pass to jsonlite::toJSON when serializing the value

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
27
28
py.assign("a", 1:4)
py.get("a")
# [1] 1 2 3 4

py.assign("b", list(one = 1, foo = "bar"))
str(py.get("b"))
# List of 2
#  $ foo: chr "bar"
#  $ one: int 1

py.exec("import math")
py.get("math.pi")
# [1] 3.141593

# by default jsonlite::toJSON is called on the value to be assigned
# with auto_unbox = TRUE, so vectors of length 1 are simplified to
# scalar values in Python
py.assign("c", "foo bar")
py.exec("crepr = repr(c)")
py.get("crepr")
# [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.assign("d", "foo bar", json.opt.args = list(auto_unbox = FALSE))
py.exec("drepr = repr(d)")
py.get("drepr")
# [1] "[u'foo bar']"

asieira/SnakeCharmR documentation built on Jan. 3, 2020, 7:27 a.m.