Movatterモバイル変換


[0]ホーム

URL:



Getting Started

Getting started

The RCall package is loaded via

julia> using RCall

This will initialize the R process in the background.

Several Ways to use RCall

RCall provides multiple ways to allow R interacting with Julia.

R REPL mode

The R REPL mode allows real time switching between the Julia prompt and R prompt. Press$ to activate the R REPL mode and the R prompt will be shown. (Pressbackspace to leave R REPL mode in case you did not know.)

julia> foo = 11R> x <- $fooR> x[1] 1

The R REPL mode supports variable substitution of Julia objects via the$ symbol. It is also possible to pass Julia expressions in the REPL mode.

R> x = $(rand(10))R> sum(x)[1] 5.097083

@rput and @rget macros

These macros transfer variables between R and Julia environments. The copied variable will have the same name as the original.

julia> z = 11julia> @rput z1R> z[1] 1R> r = 2julia> @rget r2.0julia> r2.0

It is also possible to put and get multiple variables in one line.

julia> foo = 22julia> bar = 44julia> @rput foo bar4R> foo + bar[1] 6

@R_str string macro

Another way to use RCall is theR"" string macro, it is especially useful in script files.

julia> R"rnorm(10)"RObject{RealSxp} [1] -0.72687855 -0.33970450 -0.73194258  1.03683473 -0.36328502 -0.72049376 [7] -0.62619973  0.09185129  1.16216142  2.17293414

This evaluates the expression inside the string in R, and returns the result as anRObject, which is a Julia wrapper type around an R object.

TheR"" string macro supports variable substitution of Julia objects via the$ symbol, whenever it is not valid R syntax (i.e. when not directly following a symbol or completed expression such asaa$bb):

julia> x = randn(10)10-element Array{Float64,1}:  0.4816123619498722  0.3264937624075163  1.0541193260848456 -1.302322244295568 -0.6532385852868288 -1.9367446336772407  0.8170826524159507  0.8177315590330477 -0.42775328167862064  1.396114201915309julia> R"t.test($x)"RObject{VecSxp}One Sample t-testdata:  `#JL`$xt = 0.16575, df = 9, p-value = 0.872alternative hypothesis: true mean is not equal to 095 percent confidence interval: -0.7248370  0.8394561sample estimates: mean of x0.05730951

It is also possible to pass Julia expressions which are evaluated before being passed to R: these should be included in parentheses

julia> R"optim(0, $(x -> x-cos(x)), method='BFGS')"RObject{VecSxp}$par[1] -1.56343$value[1] -1.570796$countsfunction gradient      14       13$convergence[1] 0$messageNULL

A large chunk of code could be quoted between triple string quotations

julia> y = 11julia> R"""       f <- function(x, y) x + y       ret <- f(1, $y)       """RObject{RealSxp}[1] 2

RCall API

Thereval function evaluates any given input string as R code in the R environment. The returned result is anRObject object.

julia> jmtcars = reval("mtcars");julia> names(jmtcars)11-element Array{Symbol,1}: :mpg :cyl :disp :hp :drat :wt :qsec :vs :am :gear :carbjulia> jmtcars[:mpg]RObject{RealSxp} [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4[16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7[31] 15.0 21.4julia> typeof(jmtcars)RObject{VecSxp}

Thercall function is used to construct function calls.

julia> rcall(:dim, jmtcars)RObject{IntSxp}[1] 32 11

The arguments will be implicitly converted toRObject upon evaluation.

julia> rcall(:sum, Float64[1.0, 4.0, 6.0])RObject{RealSxp}[1] 11

Thercopy function convertsRObjects to Julia objects. It uses a variety of heuristics to pick the most appropriate Julia type:

julia> rcopy(R"c(1)")1.0julia> rcopy(R"c(1, 2)")2-element Array{Float64,1}: 1.0 2.0julia> rcopy(R"list(1, 'zz')")2-element Array{Any,1}: 1.0  "zz"julia> rcopy(R"list(a = 1, b= 'zz')")DataStructures.OrderedDict{Symbol,Any} with 2 entries:  :a => 1.0  :b => "zz"

It is possible to force a specific conversion by passing the output type as the first argument:

julia> rcopy(Array{Int}, R"c(1, 2)")2-element Array{Int64,1}: 1 2

Converter could also be used specifically to yield the desired type.

julia> convert(Array{Float64}, R"c(1, 2)")2-element Array{Float64,1}: 1.0 2.0

Therobject function converts any julia object to an RObject.

julia> robject(1)RObject{IntSxp}[1] 1julia> robject(Dict(:a => 1, :b = 2))ERROR: syntax: invalid keyword argument name ":b"

@rlibrary and@rimport macros

This micro loads all exported functions/objects of an R package to the current module.

julia> @rlibrary bootjulia> city = rcopy(R"boot::city")  # get some data10×2 DataFrames.DataFrame│ Row │ u     │ x     │├─────┼───────┼───────┤│ 1   │ 138.0 │ 143.0 ││ 2   │ 93.0  │ 104.0 ││ 3   │ 61.0  │ 69.0  ││ 4   │ 179.0 │ 260.0 ││ 5   │ 48.0  │ 75.0  ││ 6   │ 37.0  │ 63.0  ││ 7   │ 29.0  │ 50.0  ││ 8   │ 23.0  │ 48.0  ││ 9   │ 30.0  │ 111.0 ││ 10  │ 2.0   │ 50.0  │julia> ratio(d, w) = sum(d[:x] .* w)/sum(d[:u] .* w)ratio (generic function with 1 method)julia> b = boot(city, ratio, R = 100, stype = "w");julia> rcall(:summary, b[:t])RObject{StrSxp}       V1 Min.   :1.201 1st Qu.:1.400 Median :1.513 Mean   :1.554 3rd Qu.:1.646 Max.   :2.819

Of course, it is highly inefficient, because the data are copying multiple times between R and Julia. TheR"" string macro is more recommended for efficiency.

Some R functions may have keyword arguments which contain dots. RCall provides a string macro to escape those keywords, e.g,

julia> @rimport base as rbasejulia> rbase.sum([1, 2, 3], var"rm.na" = true)RObject{IntSxp}[1] 7

[8]ページ先頭

©2009-2025 Movatter.jp