Subscript out of bounds, stopping for loop at the last value - r

I keep getting the error:
Error in locoh[[i + 1]] : subscript out of bounds
I'm almost certain that its because my its looking for the additional value so length(locoh) +1, but that value does not exist. How could I stop this for loop at the max extent of my object locoh?
# Estimate overlap between LoCoHs for each 10-day interval
for (i in 1:(length(locoh))){
hr_overlap(locoh[[i]], locoh[[i+1]], type = 'hr')
}
For example, I would my for loop to start from the first value in locoh, then locoh+1, locoh + 2, ..... then stop once it reaches locoh_max value. What would be the best way to do this?

Instead of loop to the length, it should be to length(locoh)-1 because locoh[[i+1]] at the last i i.e. length will be out of bounds
for (i in 1:(length(locoh)-1)){
hr_overlap(locoh[[i]], locoh[[i+1]], type = 'hr')
}

Related

Having trouble creating error statements when creating function

I am creating a function in R for calculating compound interest using the equation - F=P\left(1+\frac{i}{100t}\right)^{ty}.
I need to create error messages if any of P, i, t, or y arguments are not numeric or negative, and an error if i is out of the range 0-100.
When I try to run the code i get the error message:
Error: unexpected ',' in:
" stop("Argument 'P','i','t' and 'y' must be numeric")
if(P,"
and am unsure how to fix it or what I have done wrong. The code so far is:
compound <- function(P,i,t=12,y,plotit=FALSE,...){
# 1. Check arguments and throw errors here using 'if' statements
if(!is.numeric(P,i,t,y)){
stop("Argument 'P','i','t' and 'y' must be numeric")
if(P,i,t,y<0){
stop("Argument 'P','i','t' and 'y' must be non-negative")
if(i<0||i>100){
stop("'i' must be within the range 0-100 percent")
}
}
}
if(plotit==TRUE){
# 2. Do plot if necessary here according to 'plotit' argument
y <- floor(y)
f <- P*((1+(i/100*t))^t*y)
for(i in length(y)){
plot(f, type = 's')
}
}
else {
final.result <- f
# Calculate final result here
return(final.result)
}
}
Any help on how to improve the code would be great!
The problem is that you are passing four arguments to is.numeric(P,i,t,y). It can take only one.
if(!all(sapply(list(P,i,t,y), is.numeric)))
That will check if all arguments are numeric.
A similar problem occurs with if(P,i,t,y<0), so use:
if(!all(sapply(list(P,i,t,y), function(x) x >= 0)))
Additionally, you have nested these if statements, which means the second and the third will not be evaluated. Move them out of your first if statement.

R: invalid 'times' argument calculating CRPS

I'm trying to calculate crps using the verification package in R. The data appears to read in ok, but I get an error when trying to compute the CRPS itself: "invalid 'times' argument", however all values are real, no negative values and I'm testing for nan/na values and ignoring those. Having searched around I can't find any solution which explains why I'm getting this error. I'm reading the data in from netcdf files into larger arrays, and then computing CRPS for each grid cell in those arrays.
Any help would be greatly appreciated!
The relevant snipped from the code I'm using is:
##for each grid cell, get obs (wbarray) and 25 ensemble members of forecast eps (fcstarray)
for(x in 1:3600){
for(y in 1:1500){
obs=wbarray[x,y]
eps=fcstarray[x,y,1:25]
if(!is.na(obs)){
print(obs)
print(eps)
print("calculating CRPS - real value found")
crpsfcst=(crpsDecomposition(obs,eps)$CRPS)
CRPSfcst[x,y,w]=crpsfcst}}}
(w is specified in an earlier loop)
And the output I get:
obs: 0.3850737
eps: 0.3382506 0.3466184 0.3508921 0.3428135 0.3416993 0.3423528 0.3307764
0.3372431 0.3394377 0.3398165 0.3414395 0.3531360 0.3319155 0.3453161
0.3362813 0.3449474 0.3340050 0.3278898 0.3380596 0.3379150 0.3429202
0.3467927 0.3419354 0.3472489 0.3550797
"calculating CRPS - real value found"
Error in rep(0, nObs * (nMember +1)) : invalid 'times' argument
Calls: crpsDecomposition
Execution halted
If you type crpsDecomposition on your R command prompt you'll get the source code for the function. The first few lines show:
function (obs, eps)
{
nMember = dim(eps)[2]
nObs <- length(obs)
Since your eps data object appears to be (from your output) a one-dimensional vector, the second element of its dimension is going to be NULL, which sets nMember to NULL. Thus nObs*(nMember + 1) gets evaluated to 0. I imagine you simply need to re-examine what form eps should take because it would appear that it needs to be a matrix where each column corresponds to a different "member" (whatever that means in this context).

simulation a while loop

there might be some threads on while loops but I am struggling with them. It would be great if someone could help an R beginner out.
So I am trying to do 10000 simulations from a an out of sample regression forecast using the forecast parameters: mean, sd. Thankfully, my data is normal.
This is what I have
N<-10000
i<-1:N
k<-vector(,N)
while(i<N+1){k(,i)=vector(,rnorm(N,mean=.004546,sd=.00464163))}
...and I get this error
Error in vector(, rnorm(5000, mean = 0.004546, sd = 0.00464163)) :
invalid 'length' argument
In addition: Warning message:
In while (i < N + 1) { : the condition has length > 1 and only the first element will be used
I can't seem to get my head around it.
No reason to create a loop here. If you want to put 10000 samples, normal distributed around mean = 0.004546 and sd = 0.00464163 into vector k, just do:
k <- rnorm(10000,mean = 0.004546, sd = 0.00464163)
try this
N<-10
i<-1
k<-matrix(0,1,N)
while(i<N+1){k[i]=rnorm(1,mean=.004546,sd=.00464163)
i=i+1
}
print(k)
To solve your problem, use #Esben Friis' answer. You are taking a hard approach to an easy problem.
To adress the questions you had about the error messages you got however:
Error in vector(, rnorm(5000, mean = 0.004546, sd = 0.00464163)) :
invalid 'length' argument
This is the wrong way to go as vector() will produce a vector of a set length instead of a set of values. You are thinking about the as.vector() function:
as.vector(rnorm(5000, mean = 0.004546, sd = 0.00464163))
This is however not needed as this will only create a new vector of your values, which are already in a vector structure of the type double. Using this function will therefore not change anything.
It is best to simply use:
rnorm(5000, mean=0.004546, sd=0.00464163)
Further:
In addition: Warning message:
In while(i<N+1){: the condition has length>1 and only the first element will be used
This warning stems from i being a vector 1:N with a length larger than 1. The warning states that only the first index in i will be recycled (used in all instances of the loop) which is the same as doing i[1] .
while(i<N+1){ }
#is the same as
while(i[1]<N+1){ }
Instead you want to loop a new value to N. Furthermore you can use the <= (less or equal to) operator instead of doing <N+1 .
while(newVal<=N){ }
This method will bring up new problems which could be solved by using a for() loop instead, but that is however out of the scope of the question and really not the right approach to your problem, as stated in the beginning. Hope you learned something and good luck!

R, how to force to throw an error/warning if index exceeds matrix dimensions

The default behavior in R when the index exceeds the dimensions of a vector / matrix is to return NA. E.g.
> a = as.matrix(1:10)
> a[11]
[1] NA
This is very inconvenient in many circumstances, since the code keeps running giving wrong results and without even giving a warning.
Does anyone know if it is possible to alter this default behavior in a code, so that in these cases an error or a warning is thrown instead of returning NA when the index exceeds the dimensions of a vector/matrix ?
One solution is for you to use two arguments (row and col) when indexing your matrix with [, which is the more "normal" thing to do with a matrix. That usage will trigger an error:
a[11, 1] <- NA
# Error in `[<-`(`*tmp*`, 11, 1, value = NA) : subscript out of bounds
Another way, assuming that your a[11] is part of a script or function, is to put in your own error check. For example,
for (j in 1:20 ) {
ifelse(j <= length(a), a[j], cat('index out of bounds') )
}

error message Error in `[<-`(`*tmp*`, i, j, value = 0) : subscript out of bounds

I am using a code like
df2<-df[1:3000,]
tail(df2)
df4<-(table(df2)>0)*1
dim(df4)
m.adj<-matrix(0,nc=1:5217,nr=5217)
for(i in 1:5215){
for(j in (i+1):5216){
m.adj[i,j]<-sum(df2[,i]*df2[,j])
}
}
Error in `[<-`(`*tmp*`, i, j, value = NA_integer_) :
subscript out of bounds
it gives me an error( above) I am not able to find the solution for it .any suggestion will highly be appreciated. thanks in advance
This error tells you that the subscript you trying to get in m.adj is exceeding the size of this matrix.
The size of m.adj is 5217 x 1, because you defined it in this way: m.adj<-matrix(0,nc=1:5217,nr=5217) whereas it should be defined in this way:
m.adj<-matrix(0,nc=5217,nr=5217)
because the argument nc must be an integer and not an array of integers. Otherwise it takes the first element of the array. And here it is one.
Therefore, you just need to put in your code m.adj<-matrix(0,nc=5217,nr=5217)
and it should work!

Resources