R - Creating a class with a list attribute - r

I am pretty new using R in an advanced way...so apologize for futile questions!
I want to create a object of class S4, defined by 3 slots. Thing is that I can't manage to create these attributes as a list. Here is my code :
test<-setClass("dblist",representation(df.list="list", df.para="list",df.coups="list"))
new("dblist",representation(df.list="list", df.para="list",df.coups="list"))
and the error I get :
Error in initialize(value, ...) : cannot use object of class “list” in new(): class
“dblistpgn” does not extend that class
Could you please explain how creating an object with list plot?
Thx!

try this:
new("dblist", df.list = list(), df.para = list(), df.coups = list())

Related

Trying to access R class methods and fields within Python using rpy2

I am using rpy2 to import a library from CRAN repository called "MatrixEQTL" to run in within Python using importr, here is my attempt:
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
robjects.r('install.packages("MatrixEQTL")')
mtrql = importr('MatrixEQTL')
I am trying to access both class fields as well as class methods but I failed here is what the class looks like when printing into the python shell:
# to view class SlicedData of MatrixEQTL R package
print(mtrql.SlicedData)
Generator for class "SlicedData":
Class fields:
Name: dataEnv nSlices1 rowNameSlices
Class: environment numeric list
Name: columnNames fileDelimiter fileSkipColumns
Class: character character numeric
Name: fileSkipRows fileSliceSize fileOmitCharacters
Class: numeric numeric character
Class Methods:
"Clear", "show#envRefClass", "nSlices", "getRefClass", "export",
"initialize", "CombineInOneSlice", "callSuper", "initFields", "nCols",
"getClass", "RowStandardizeCentered", "import", "SaveFile", "RowReorder",
"setSlice", "getSlice", "RowReorderSimple", "CreateFromMatrix", "nRows",
"ResliceCombined", "LoadFile", "ColumnSubsample", "SetNanRowMean",
"setSliceRaw", "getSliceRaw", "copy", "RowMatrixMultiply", "usingMethods",
"GetAllRowNames", "RowRemoveZeroEps", "field", ".objectParent",
"IsCombined", "untrace", "trace", "Clone", "GetNRowsInSlice",
".objectPackage", "show", "FindRow"
Reference Superclasses:
"envRefClass"
I want to access for instance class field say fileDelimiter and also class Methods say LoadFile but I couldn't, here is also my attempt to access class method LoadFile and the error message that generated:
# If I try to run this without "()"
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'DocumentedSTFunction' object has no attribute 'LoadFile'
# And that's my attempt for when adding "()" to the class name
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'RS4' object has no attribute 'LoadFile'
I tried to look for a solution to this issue but I wasn't successful, please help me understand and solve this issue.
Thank you so much in advance.
mtrql.SlicedData is a "Generator", that is a constructor. In R that means a function (that will return an instance of the class), which is why mtrql.SlicedData is an R function with rpy2.
Consider the following example from the R documentation (https://rdrr.io/r/methods/Introduction.html):
import rpy2.robjects as ro
Pos = ro.r("""
setClass("Pos", slots = c(latitude = "numeric", longitude = "numeric",
altitude = "numeric"))
""")
With rpy2, the object Pos is an R function:
>>> type(Pos)
rpy2.robjects.functions.SignatureTranslatedFunction
However that function object has an S3 class in R (there are several OOP systems in R, 2 of them coexisting in standard R unfortunately).
>>> tuple(Pos.rclass)
('classGeneratorFunction',)
A specific print function is implemented for this S3 class, and it will use the attributes package and className for the object (the R function-that-is-in-fact-a-Generator) to display all the info about the clas you are seeing.
Since this is a constructor, to create an instance you can do:
pos = Pos()
or
pos = Pos(latitude=0, longitude=0, altitude=-10)
The instance will have instance attributes (and methods)
>>> tuple(pos.list_attrs())
('latitude', 'longitude', 'altitude', 'class')
>>> tuple(pos.do_slot('altitude'))
(-10,)
With your specific example, you probably want something like:
slidata = mtrql.SlicedData()
slidata.do_slot('LoadFile')(file)
The documentation can provide more information about R S4 classes in rpy2, and how to make wrapper classes in Python that map attributes and methods.
https://rpy2.github.io/doc/v3.3.x/html/robjects_oop.html#s4-objects

unused argument error when printing from RC class method

I am creating an RC class and while trying to print(.self$something) within a class method I am getting:
Error in print(.self$something) : unused argument (.self$something)
I am sort of new to R, so am I missing something here?
This is for an assignment which asks us to use RC classes, using R6 is not an option.
myclass <- setRefClass("myclass",
fields = list (
formula = "formula",
data = "data.frame",
something = "numeric"
),
methods = list (
initialize = function(formula, data) {
...
},
print = function() {
...
print(.self$something)
},
)
)
a <- myclass$new(formula,data)
a$print()
> Error in print(.self$something) : unused argument (.self$something)
Edit: Extra info, if I try a$something I get what I should get.
Try to use cat in your print function, you are now in your local print function environment and trying to call your system "print" function. I suggest you use cat as follows:
cat(.self$something)
It will do the job
As #Mohammed mentions, this happened because I was in printing within my own print environment. Though cat() could be an option, later I faced other issues in which cat did not print the object (that could be a thread on its own so I will not go deeper on that here).
What I ended up doing was calling the print function for that specific data type. For instance, if something was a data.frame I called print.data.frame(.self$something) and worked as expected.

How to inherit stan's S4 class

I develop some package using rstan::stan(). I make a function whose return value is an S4 class object generated by rstan::stan(). To access estimates comfortablely or to add an information for data, I want to make a new S4 class object which inherits S4 class of rstan::stan()so that there is new slots.
Furthermore, the new S4class object also can be available for any functions in rstan such as rstan::traceplot().
fit <- rstan::stan( model_name=scr, data=data) # This is a fictitious code.
Suppose we get S4 (stanfit) object named fit .
Define an extended class of stanfit
InheritedClass <- setClass("InheritedClass",
# New slots
representation(slotA="character",
slotB="character",
slotC="numeric"),
contains = "stanfit"
)
To create an S4 object of the inherited class using an existing S4 class object ,i.e., fit,
so what I need is only to input values for added new slots, i.e., slotA, slotB, slotC.
Using the following code, we can convert the S4 object for old class to inherited class:
fit2 <- as(fit,"InheritedClass")
Using this we can edit slot like following:
fit2#slotA <- "aaaaaaaaaaaa"
See help(setClass). I believe it would be something like
setClass("classname", slots = c(foo = "numeric", bar = "character"),
contains = "stanfit")
And I'm sure you would have to include rstan in the Imports: line of the DESCRIPTION file in your package in order for it to find the S4 class definition for stanfit.

R Instance of S4 object with S3 attribute

I am currently creating a new S4 class which uses a S3 zoo object. I can create a class
setOldClass("zoo")
setClass("rollingSD", slot = c(rollPeriod = "numeric", tsOutput = "zoo"))
This code works fine. Now if I want to create an object as
riskSD <- new("rollingSD")
This also works fine. However, the following generates an error
riskSD <- new("rollingSD", rollPeriod = 12)
Error in validObject(.Object) :
invalid class “rollingSD” object: invalid object for slot "tsOutput" in class
"rollingSD": got class "S4", should be or extend class "zoo"
This not clear for me why a default object of the zoo class is not inititated. I also do not know how to fix this.
The problem is caused because R's class mechanism doesn't know how to make a new zoo object. You can fix this by specifying a "prototype":
setClass(
"rollingSD",
slot = c(rollPeriod = "numeric", tsOutput = "zoo"),
prototype=prototype(
tsOutput=some_zoo_object
)
)
where some_zoo_object is of class zoo. The default prototype for a numeric slot is numeric(), but because you defined the (S4) class zoo yourself, the default is new("zoo") and this isn't defined.

“guiWidgetsToolkittcltk” is not a defined class

I want to create GUI using gWidget in R but I am getting all these kind of weird errors:
guitoolkit = new("guiWidgetsToolkittcltk")
Error in getClass(Class, where = topenv(parent.frame())) :
“guiWidgetsToolkittcltk” is not a defined class
or:
> setIs("guiWidget","guiWidgetORgWidgetTcltkORtcltk")
Error in .walkClassGraph(classDef, "subclasses", where) :
the 'subClass' list for class “guiWidgetORgWidgetTcltkORtcltk”, includes an undefined class “guiWidget”
Any idea what I am missing?

Resources