JuliaInterop / JuliaCall

Embed Julia in R
https://non-contradiction.github.io/JuliaCall/index.html
Other
267 stars 36 forks source link

Feature Request: julia_assignFloat32 #170

Closed jpkrooney closed 3 years ago

jpkrooney commented 3 years ago

Hi, I was wondering would it be possible to get a function that assigns data from R directly info a Float32? The reason is for performance enhancements. I don't need 64bit precision, however when I send numeric array to Julia via julia_assign, Julia will make it a Float64(T, N). Yes, I could then convert it to Float32, but that itself takes a little time and therefore eats up any gains made elsewhere in the code by using Float32. If there was a command to assign data from R directly to Float32, this would cut out the conversion step and restore gains. Hopefully this would be possible.

In any case - thank you very much for this great package.

Non-Contradiction commented 3 years ago

Thanks for the feedback!

It should be possible as follows.

> julia_command("import RCall.rcopytype; rcopytype(::Type{RCall.RClass{:JuliaFloat32}}, x::Ptr{RealSxp}) = Array{Float32}")
rcopytype (generic function with 17 methods)

> julia_assign("a", structure(c(1.0,2.0), class = "JuliaFloat32"))
> julia_command("a")
2-element Array{Float32,1}:
 1.0
 2.0

> 

The first command tells that JuliaCall should convert R objects of type double with class JuliaFloat32 to julia Array with Float32 type. structure(c(1.0,2.0), class = "JuliaFloat32") constructs an R object c(1.0, 2.0) with class label "JuliaFloat32". Then JuliaCall knows how to convert the object by the last command.

Hope this helps!

I think I need to wrap up some documentation materials on this when I have more time...

jpkrooney commented 3 years ago

Wow thanks I'll try it out. Alas, I think in the end I will need 64bit precision anyway, but it is good to know how to do this for future reference!