On Thu, 20 Oct 2016, Sven Schreiber wrote:
Hello,
I'm testing the feature from the section "Further use of the R library" of
the gretl guide (36.7), namely that I can define my own R functions in a
foreign block and call them later. (Which is great!) I'm struggling with some
limitations when I want to get matrices back, and I'm not sure whether those
are bugs or not. Sometimes I'm only getting the first element of the return
matrix, and sometimes there seems to be some unwanted rounding going on.
Below are some examples (sorry a bit long, but just because it's repetitive).
Thanks,
Sven
<hansl>
set R_functions on
# matrix in / matrix out (or scalar in /scalar out)
foreign language=R
check1 <- function(x) {
options(digits=10)
return(x)
}
end foreign
# scalar in / matrix out (or matrix in / matrix out)
foreign language=R
check2 <- function(x) {
options(digits=10)
z <- c(x, x)
return(z)
}
end foreign
# both scalar and matrix in / matrix out
foreign language=R
check3 <- function(x, y) {
options(digits=10)
z <- c(x, y)
return(z)
}
end foreign
### calls from hansl
scalar ins = 10
matrix inm = {123456.9, 0}
matrix heym = R.check1(inm) # works
eval heym
scalar heys = R.check1(ins) # works
eval heys
matrix hus = R.check2(ins) # fails
eval hus
matrix hum = R.check2(inm) # fails
eval hum
matrix ouf = R.check3(ins, inm) # fails
eval ouf
The rounding is just a matter of the default number of digits shown
by gretl.
Besides that, you need to give gretl a little help with the return
types, using as.matrix() as required (an R "list" doesn't map onto a
gretl type). Here's an illustrative rewrite:
<hansl>
set R_functions on
# matrix in / matrix out (or scalar in /scalar out)
foreign language=R
check1 <- function(x) {
options(digits=10)
return(x)
}
end foreign
# scalar in / matrix out (or matrix in / matrix out)
foreign language=R
check2 <- function(x) {
options(digits=10)
z <- c(x, x)
return(as.matrix(z))
}
end foreign
# both scalar and matrix in / matrix out
foreign language=R
check3 <- function(x, y) {
options(digits=10)
z <- c(x, y)
return(as.matrix(z))
}
end foreign
set echo off
set messages off
### calls from hansl
scalar ins = 10
printf "ins = %.7g\n", ins
matrix inm = {123456.9, 0}
printf "inm:\n%13.7g\n", inm
matrix heym = R.check1(inm)
printf "heym = R.check1(inm):\n%13.7g\n", heym
scalar heys = R.check1(ins)
printf "heys = R.check1(ins) = %.7g\n", heys
matrix hus = R.check2(ins)
printf "hus = R.check2(ins):\n%13.7g\n", hus
matrix hum = R.check2(inm)
printf "hum = R.check2(inm):\n%13.7g\n", hum
matrix ouf = R.check3(ins, inm)
printf "ouf = R.check3(ins, inm):\n%13.7g\n", ouf
</hansl>
Allin