Getting a Slot's Value of S4 Objects

Getting a slot's value of S4 objects?

First off, you should be aware that the @area slot is not a reliable source of information about a SpatialPolygons* object's actual area. As noted in ?"Polygons-class", the @area slot is just used as an adjunct to plotting (preventing smaller polygons from getting painted over by larger ones) and does not respect projection or properly account for holes in polygons.

To get accurate areas, you should instead use rgeos::gArea() for layers with projected coordinate reference systems or geosphere::areaPolygon() for those in lat-long coordinate reference systems (i.e. CRS(+proj=longlat)).

With those caveats out of the way, the following shows how you can get the contents of the @area slots if you do in fact want them.


The main complication is that the area slot belongs to the Polygon object, not to the SpatialPolygons object (of which the Polygon object is one element). You thus need to first dig down into the SpatialPolygons object to extract to the individual Polygon object(s).

One you have done that, you can just use the @ operator to extract the contents of the area slot.

The following example uses the SpatialPolygons object created in Section 7 of the sp package vignette (warning, pdf):

require(sp)
# Example pasted in from Section 7 of the sp vignette
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

# To extract the area of the first (or in your case only) Polygon
SpP@polygons[[1]]@area
# [1] 5.5

# Extract the areas of all three component Polygons
sapply(SpP@polygons, function(x) x@area)
# [1] 5.5 1.5 10.0

## For areas, rgeos::gArea() or geosphere::areaPolygons() are generally more appropriate
## (Note, for instance, that it properly accounts for the hole in the 3rd polygon.)
rgeos::gArea(SpP, byid=TRUE)
# s1 s2 s3/4
# 5.5 1.5 9.0

R: get value of a slot from S4 object(ScalarIndependenceTest)

The print equivalent for S4 classes is the show method, which can be inspected using getMethod. In this case,

ss
#
# Exact Wilcoxon-Mann-Whitney Test
#
#data: v by g (GroupA, GroupB)
#Z = -2.1095, p-value = 0.0385
#alternative hypothesis: true mu is not equal to 0

getMethod("show","ScalarIndependenceTest")
#Method Definition:
#
# function (object)
# {
# distname <- switch(class(object@distribution), AsymptNullDistribution = "Asymptotic",
# ApproxNullDistribution = "Approximative", ExactNullDistribution = "Exact")
# RET <- list(statistic = setNames(object@statistic@teststatistic,
# nm = "Z"), p.value = object@distribution@pvalue(object@statistic@teststatistic),
# alternative = object@statistic@alternative, data.name = varnames(object@statistic),
# method = paste(distname, object@method))
#...
#...
# }

ss@statistic@teststatistic
# GroupA
#-2.109531

ss@distribution@pvalue(ss@statistic@teststatistic)
#[1] 0.03850484

access the data inside the slots of S4 objects

It really is just standard S4, so you need to pick element by element. Here is an example which I have actually wrapped in C++ as an RInside example:

suppressMessages(library(fPortfolio))
lppData <- 100 * LPP2005.RET[, 1:6]
ewSpec <- portfolioSpec()
nAssets <- ncol(lppData)

weightsvec <- c(0.5, rep(0.1, 5))
setWeights(ewSpec) <- weightsvec
ewPf <- feasiblePortfolio(data=lppData, spec=ewSpec, constraints="LongOnly")
print(ewPf)
vec <- getCovRiskBudgets(ewPf@portfolio)

Here, you simply read the str() output wrong and omitted a layer of @portfoio (Hint: you need two) when trying to get to weights:

R> ewPf@portfolio@portfolio$weights
SBI SPI SII LMI MPI ALT
0.5 0.1 0.1 0.1 0.1 0.1
R>

which are of course the same six values I gave it earlier in the example.

Edit: Your subsequent edits proves this. You have

> str(frontier@portfolio)
Formal class 'fPFOLIOVAL' [package "fPortfolio"] with 2 slots
..@ portfolio:List of 7
.. ..$ weights : num [1:49, 1:14] 0.0805 0.161 0.2415 0.322 0.4025 ..

which is precisely the frontier@portfolio@portfolio$weights I show in my code (albeit applied to the variable named the way it is in your example).

how to set value in S4 object r using a method (no input value needed)

It seems overriding the initialize method worked for me. For example

setClass("Person",
representation(name = "character", age = "numeric", doubleAge = "numeric"),
prototype(name = "Bob", age = 5, doubleAge = 10) )

setMethod("initialize", "Person", function(.Object, ...) {
.Object <- callNextMethod()
.Object@doubleAge <- .Object@age*2
.Object
})

(p1 <- new("Person", name = "Alice", age = 6))
# An object of class "Person"
# Slot "name":
# [1] "Alice"
# Slot "age":
# [1] 6
# Slot "doubleAge":
# [1] 12

The callNextMethod() runs the "default" initializer to set up all the values that we are not messing with. Then we just change the values we want and return the updated object.

Access slot from S4 object in a list within an R loop

You cannot use the $ operator this way - you have to use the [[ operator instead. So if your structure is set up as you describe, that is you have lists called a_vcf, b_vcf, c_vcf, each of which contains an element with the same name, then the following will work:

for(i in mysamples){
vcf <- mget(i)
a <- vcf[[i]]@rowRanges
}

However, please remember you are over-writing a each time, so after the loop completes, you will only have the value of c_vcf$c_vcf@rowRanges written to a.

How to set the value of a slot(S4) using - in R

The problem is solved. Name of the last argument of the function must be value.

setGeneric("name", function(object) standardGeneric("name"))
setMethod("name", "markovchain", function(object) {
out <- object@name
return(out)
})

setGeneric("name<-", function(object, value) standardGeneric("name<-"))
setMethod("name<-", "markovchain",
function(object, value) {
object@name <- value
object
}
)

See the output.

> name(ob)
[1] "deepak"
> name(ob) <- "value is changed"
> name(ob)
[1] "value is changed"


Related Topics



Leave a reply



Submit