S4 object in R cannot be passed to Fortran - r

I use the bdiag function in the Matrix package in R to generate diagonal matrix, and then I pass the resultant matrix (called mat) into a self-written function but R fails to execute due to the following error:
Error: invalid mode (S4) to pass to Fortran (arg 1)
I checked isS4(mat) and it's TRUE. Thus, I guess there is a way to convert the S4 object somehow in order to be passed to the function. Any advice will be greatly appreciated!
UPDATE: I use the following codes for constructing the block diagonal matrix:
grp.ids <- as.factor(c(rep(1,8), rep(2,4), rep(3,2)))
x <- model.matrix(~grp.ids)
X <- do.call(bdiag, replicate(238, x, simplify=FALSE))
Is there any other way to get a S3 matrix without using the bdiag function? Thanks!

Only the .Call() interface can pass full R objects down to C or C++ code, see Section 5 of the Writing R Extensions manual. With .Fortran() and .C() you are limited to basic vectors of int, double, ... and their corresponding Fortran types.

Related

Handling matrices using Brobdingnag package

I need to build a matrix with extremely small entries.
So far I realized that the fastest way to define the kind of matrix that I need is:
Define a vectorized function of coordinates:
func = function(m,n){...}
Combine every possible coordinate using outer:
matrix = outer(1:100,1:100,FUN=func)
Having to deal with extremely small numbers I work in func's environment using brob numbers, its output will therefore be of the same type of a brob:
typeof(func(0:100,0:100) )
[1] "S4"
If I directly plug two vectors 0:100 in my function func it returns a vector of brobs but if I try to use it with outer I get the error:
Error in outer(1:100, 1:100, FUN = func) : invalid first argument
I suppose this is because package Brobdingnag can somehow deal with vectors but not with matrices. Is it right? Is there any way to make it work?

R: How to use named vector to initialize parameter values in mle2

I am a beginner in R and need to use it to estimate a MLE. I am using the mle2 function. However since i have many independent variables, I need to pass many parameter values when calling mle2. For example
library(bbmle)
x <- mle2(probit, start=list(b0=1,b1=1,b2=1,c0=1,c1=1,d0=1,d1=1),method="BFGS")
Instead, I would like to create a vector theta of length 7 and pass that when i call mle2. Something like
x <- mle2(probit, start=theta,method="BFGS")
Exactly this does not work. Do I need to change how I define the function probit accordingly to use a vector as argument?
I went through the existing threads related to passing vectors as arguments and they suggest using do.call, but can that be used to call mle2? If so, how?
many thanks!
If I understand correctly, your goal is to reduce boilerplate by finding a way to pass a single vector of parameter values. You could achieve this by defining a utility function which converts a single vector of un-named entries into a named list suitable for your model and for mle2:
## vector of un-named entries
theta <- c(1,1,1,1,1,1,1)
## utility function
toList <- function(th) structure(as.list(th), names=c("b0","b1","b2","c0","c1","d0","d1"))
## check
identical(toList(theta), list(b0=1,b1=1,b2=1,c0=1,c1=1,d0=1,d1=1))
## now this should work
x <- mle2(probit, start=toList(theta), method="BFGS")

R, calling Matrix package within function

I am using the package Matrix to create a sparse matrix inside a function that is contained in my personal R package, say
myfun <- function(x, ...){
d = Matrix(0, 5, 5, sparse = TRUE)
d[seq(1,25, by=x)] = 1
t(d)
}
( class(d) is "dgCMatrix" )
If I declare the function in the general environment and I run it from the console, everything works. However, when it is called from the package, I get
Error in t.default(D) : argument is not a matrix
Essentially R tries to call the t() function from the base environment, instead of the version of t() provided with the Matrix package, that possesses the methods to handle dgCMatrix class objects.
I tried explicitly calling library(Matrix) from within the function, but it does not help.
I had the same problem with another function, colSums(), and I solved it using Matrix::colSums() instead. However I would like to find a more general and practical remedy, instead of specifying the environment for every function.
I stress the fact that if I load the function in the general environment, R correctly loads the functions from Matrix.
Any idea on the source of the problem, or how I can force R to read from Matrix these functions?

coerce class data type in R with as

I understand that in R you have some base data types (vector, matrix, list, data.frame) and then in the R packages you have some advanced types called S3-class or S4-class (ppp,owin, spatialPointsDataFrame and many others. Some of the functions in R packages only work with arguments of special type.
I need explanation about converting between different classes and data types in R:
Sometimes I can use a code like:
m = c(1, 2, 3, 4)
df = as.data.frame(m)
But in other cases I must use a code like:
shp = readShapeSpatial("polygons.shp")
win = as(shp,"owin")
How do I know which syntax of the as to use for which object?
Or is the syntax: as.foo(originalObject) always equivalent to as(originalObject, "foo") (here foo stands for the class that I want to convert my object to so that I can use in a function that requires its argument to be a foo class)
Let's say I use a package in R with a class foo. And I have a variable v that belongs to class bar (in other words, class(v) is bar). How do I know if the function as(v,"foo") will work?
as.data.frame is an S3 method that you can check for foo using :
getS3method('as.data.frame','foo')
But I think you are looking for ( as it is commented)
showMethods(coerce)
This will give you a list of predefined coerce funsctions.
To define you coerce function , one option (there are many options like setIS , coerce<- and implicit coercion through inheritance) is to use setAs. Here an example:
track <- setClass("track",
slots = c(x="numeric", y="numeric"))
setAs("track", "numeric", function(from) from#y)
t1 <- new("track", x=1:20, y=(1:20)^2)
as(t1, "numeric")
Now if I check using :
showMethods(coerce)
You get an entry with :
from="track", to="numeric"
For better explanation you should read help("as") but the subject is not very simple.
EDIT To show only the entries with track you can do this for example:
cat(grep('track',showMethods(coerce,printTo=FALSE),value=TRUE))
from="track", to="numeric"

R List data Type in Fortran

I need help representing R data type in Fortran.
My R code:
mList <- list()
I want to use mList in a Fortran function by passing it as an argument to the Fortran function. What is the corresponding R list() data type in Fortran?
My Fortran code
function fun(mList)
<XXX> mList
...
end function
What should I have in place of XXX?

Resources