I'm looking into the behavior of R, and figured out something wierd.
I will use the package geoR as a reference, since it is the package I am working with.
I seem not to grasp how subsetting lists work. I have the following code.
install.packages("geoR", dependencies = T)
library(geoR)
v.1 <- variog(wolfcamp)
v.2 <- variog(wolfcamp, trend = "1st")
vg <- list(v.1, v.2)
names(vg) <- c("Constant", "Linear")
In which I create two variograms (the nature of these functions is not relevant). These are objects of class "variogram", as one can quickly check.
Inside each variogram there are two vectors, "u" and "v", that I want to extract. Since I put them in a list, I expect to be able to retrieve them with simple subsetting.
>vg[1]$Constant$u
[1] 16.77718 50.33154 83.88591 117.44027 150.99463 184.54899 218.10335
[8] 251.65772 285.21208 318.76644 352.32080 385.87517 419.42953
>vg[1]$Constant$v
[1] 1796.634 3690.930 7857.991 12440.353 23165.716 31798.304
[7] 38956.743 52007.883 67601.931 94523.535 159900.019 186464.824
[13] 219033.678
Now, if I call the same object with the middle subset in quote, I get the same result.
> vg[1]$"Constant"$u
[1] 16.77718 50.33154 83.88591 117.44027 150.99463 184.54899 218.10335
[8] 251.65772 285.21208 318.76644 352.32080 385.87517 419.42953
But if I call the subset on the output of a function or an object defined as an output of a function, the output is not the same.
k <- names(vg)[1]
> vg[1]$k$u
NULL
Why does this happen? Does it have to do with the nitty gritty of how the class variogram is defined or is there something I don't get about list subsetting? Thank you
It is not related to the class
'variogram', but is a general behavior to extract the list
elements when we pass the objects. The structure of the list
can be found by using str(vg)
.
The way we extract a single list
element is using [[
. This works both for the objects as well as names of the elements or index i.e. if we want to extract using the object 'k'
vg[[k]]$u
#[1] 16.77718 50.33154 83.88591 117.44027 150.99463 184.54899 218.10335 251.65772 285.21208 318.76644
#[11] 352.32080 385.87517 419.42953
Note that, the vg[1]
is not used and it is not required as the vg[1]
is still not extracting the 'Constant' element.
vg[[1]]$u
#[1] 16.77718 50.33154 83.88591 117.44027 150.99463 184.54899 218.10335 251.65772 285.21208 318.76644
#[11] 352.32080 385.87517 419.42953
where 1 is the first list element i.e. 'Constant'
If we are using the names itself
vg[['Constant']]$u