What does #lx[i] mean in R? - r

So i looked into a guy's code and i saw these lines of code:
for(i in 1:getOmega(bh_w_f) + 1){
bh_w_f_qx[i] = (bh_w_f#lx[i] - bh_w_f#lx[i + 1])/bh_w_f#lx[i]
What does #lx[i] mean or do? I tried look it up on the internet but i could not find anything. Any ideas? I want to mention that these lines of code above are the first occurance of #lx[i] or lx[i] or lx alone, so no declaration before. I ran the code and it works, no error given, the function works properly.
bh_w_f_qx and bh_w_f are vectors declared before
EDIT : As said in the comments and in the first answer, bh_w_f is actually a S4 object, a lifetable made with function probs2lifetable from https://www.rdocumentation.org/packages/lifecontingencies/versions/1.3.7/topics/probs2lifetable but i could not find what lx wants to be. As i said, it's the first time that lx shows up in the code, with no external files included.
EDIT 2: Found out that the answer is in the returning format from probs2lifetable() function, that returns a lifetable class object which has lxas representing the number of lives at the beginning of age (x).
More about it here: https://www.rdocumentation.org/packages/lifecontingencies/versions/1.3.7/topics/lifetable-class
Thanks

# is the symbol used to pull attributes from S4 class objects in R. This syntax can be unusual because most people use S3 as it's simpler than S4. In the case of the code you posted, my guess is that you can get away with thinking of # as the equivalent of a $ for lists and data frames etc.

Related

update function in R

I am trying to use update function on survey.design object. For instance, I want to create a variable that is the mean of 4 other variables, as follows
x1<-runif(3)
x2<-runif(3)
x3<-runif(3)
population=10000
testdf<-data.frame(x1,x2,x3,population)
testsvy<-svydesign(id=~1,weights=c(30,30,30),data=testdf)
testsvy<-update(testsvy,avg=mean(c(x1,x2,x3)))
However this returns a vector of the same number for every person. There must be something wrong. Alternatively I can modify on test$variables, but I don't feel that this is the easiest way...
OK I got the answer myself... Hope that it could be simpler since I type the object names three times...
testsvy<-update(testsvy,avg2=rowMeans(testsvy$variables[,c("x1","x2","x3")],na.rm=TRUE))

Error while grouping variables usuing describeBy function

I am just starting to learn R.
Used function psych::describeBy in order to group observation in standard dataset airquality.
psych::describeBy(airquality, group = df$month)
However, got the error message:
"df$month : object of type 'closure' is not subsettable"
Still, cannot understand what is wrong.
UPDATE:
Ok, this question was my first shot on Stack Overflow. Not particularly successful, but I was doing my best :). Decided not to delete it, in case it may be useful for somebody who is doing his first steps (and to humble myself too).
What I did not realize, when I was dealing with this problem years ago, is that I need to specify my column for grouping using the name of dataset airquality$Month, rather than df$Month. It was not a spelling issue, but the misunderstanding of syntax basics. I believed that I've already stated that I want to use dataframe named airquality, therefore I can address its columns by name df$Month, meaning that df is a placeholder for airquality. Which is totally wrong, of course. However, my intuition was not 100% wrong, in fact this could have been accomplished by using this syntax:
psych::describeBy(airquality, group = "Month")
You don't need to wrote name of dataframe (because you named it in first argument for function describeBy), just need to specify name of column of interest as second argument (as string, therefore in quotation marks).
Also, for some reason I wrote month, but correct name of column is Month (maybe it was renamed I am not sure).
Hope that my blunder would be a help for somebody else!
Most likely the issue is with how you're loading/using the dataset. Make sure refer to the dataset in a consistent manner
You can try something like
library(psych)
describeBy(airquality, group = airquality$month)

Working with "..." input in R function

I am putting together an R function that takes some undefined input through the ... argument described in the docs as:
"..." the special variable length argument ***
The idea is that the user will enter a number of column names here, each belonging to a dataset also specified by the user. These columns will then be cross-tabulated in comparison to the dependent variable by tapply. The function is to return a table (independent variable x indedependent variable).
Thus, I tried:
plotter=function(dataset, dependent_variable, ...)
{
indi_variables=list(...); # making a list of the ... input as described in the docs
result=with (dataset, tapply(dependent_variable, indi_variables, mean); # this fails
}
I figured this should work as tapply can take a list as input.
But it does not in this case ('Error in tapply...arguments must have same length') and I think it is because indi_variables is a list of strings.
If I input the contents of the list by hand and leave out the quotation marks, everything works just fine.
However, if the user feeds the function the column names as non-strings, R will interpret them as variable names; and I cannot figure out how to transform the list indi_variables in the right way, unsuccessfully trying things like this:
indi_variables=lapply(indi_variables, as.factor)
So I am wondering
What causes the error described above? Is my interpretation correct?
How would one go about transforming the list created through ... in the right way?
Is there an overall better way of doing this, in the input or the implementation of tapply?
Any help is much appreciated!
Thanks to Joran's helpful reading, I have come up with these improvements than make things work out...
indi_variables=substitute(list(...));
result=with (dataset, tapply(dependent_variable, eval(indi_variables, dataset), FUN=mean));

Create a loop for a list of list from RasterBrick in R

I'm on a project in remote sensing running on R. I've got a RasterBrick(x) with the raster for all the dates I'm interested in, a Time Serie with the dates corresponding (called time in the function), and a function which works as I want it when processed manually (z is the pixel I want) :
function(x,z)
{
d<-bfastts(as.vector(x[as.numeric(z)]),time,type="16-day")
n<-bfast(d, h=0.15, season="harmonic", max.iter = 1)
l[[z]]<-list(n$output[[1]]$Tt)
}
The bfastts function is used to create a ts object containing the values of one pixel along the time serie, the bfast is another processing some statisticals of which I only want one result (this is the third line)? None of this two functions are mine, and they are stable and foundable in the R package repository.
So, I would like to add "another level" of function (sorry for my vocabulary which may not be very precise) which would allow to run this function automatically. My expected result would be a list of the result of the function above, so in other words a list of each pixel's time series.
I've tried this (x is still the RasterBrick) :
function(x)
{
z<-nrow(x)*ncol(x)
j<-last(z[[1]])
l<-vector('list',length = j)
index<-function(x)
{
d<-bfastts(as.vector(x[as.numeric(z)]),time,type="16-day")
n<-bfast(d, h=0.15, season="harmonic", max.iter = 1)
l[[z]]<-list(n$output[[1]]$Tt) # this is to add the newly created element to the list
}
lapply(x, FUN='index')
}
but I'm getting an answer that it is not possible to coerce a S4 object to a vector, I guess the problem is in lapply who doesn't like the RasterBrick class... Furthermore I want a list of list in output, and not a list of RasterBrick (I think I understood lapply returns a list of object with the same class as x).
I've tried different workaround, none succesfully, which is not surprising giving my low level in programming, and this one seems to me the closest to what I need. I don't think I fully understand neither how lapply works nor the use of a function in a function.
Thank you very much if you can help me.
Cheers
Guillaume
So, in case it could be useful to someone, here is how I solved this problem (it seems rather very simple finally), the "brick" object is the RasterBrick:
pixelts<- as.list(as.data.frame(t(as.data.frame(brick))))

Questions regarding the use of S4 methods in R

We were trying to program object oriented programming in R, using S4 methods. During our programming process, we came across some problems. Apparently, the use of S4 methods is not very well documented on the internet yet, therefore we hope that we can get answers to some of our questions here.
First question:
We were trying to make a vector/array/list.. of empty S4 objects. Searching the internet brought us to the following question in this forum:
Create a vector of empty S4 objects
As (similarly) described in one of the answers to the question above, we used the following code to create a list of empty S4 objects:
setClass("Name", representation(pos_x = "numeric", pos_y = "numeric", found =
"logical"), prototype(found = FALSE))
newList <- lapply(rep("Name", 2), new)
This works perfectly fine. However, when we are trying to call one slot (one variable) of the S4 method, this won't work. When we for example want to call the slot "pos_x", the following code
newList[1]#pos_x
is not working. The error message we receive is "Trying to get slot pos_x from an object of a basic class ("list") with no slots.
So, it seems as if the slots were not assigned to the S4 method, although they are clearly defined in the list.
Does anyone know how we can call a slot from one of the S4-methods/objects of the list?
Second question:
We would like to test whether one of the elements of the list above equals "NULL", as we would like to create the objects later on.
To check this, we tried:
newList[1] == NULL
This is however only resulting in "logical(0)".
Does anyone know how to do this?
Suggestions, remarks and questions are very welcome.
Thanks a lot!
The problem is maybe due to the use of [ instead of [[.
The command newList[1] returns a list of length one, whereas the command newList[[1]] returns an element of the list. You should therefore try:
newList[[1]]#pos_x

Resources