-1

I want to use the function to calculate the arl of cusum however I meet a problem when I run the code it shows "Error in if (r[i] > h1) break : missing value where TRUE/FALSE needed" to me. I don't know how to write the correct code

myfun2<-function(c1,h1){
r=rep(0,500)
for (i in 1:499){
r[i+1]<-max(0,c1[i]+0.85*r[i])
(arl<-i)
if(r[i]>h1) break 
}
result<-arl
}
m=sapply(c,h=0.1865,myfun2)
jackray
  • 15
  • 6
  • 1
    In your `sapply` call you refer to `h=0.1865` instead of `h1`, thus, `h1` in missing in the `if` clause – Tom Mar 03 '18 at 07:54
  • 2
    Further: `sapply()` is splitting your vector `c` to elements and puts the elements one by one to your function. So you can not use `c1[i]` in your function. Is `c` a vector? Or is it a list of vectors? Please edit your question to make it [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – jogo Mar 03 '18 at 08:04
  • @Tom due to partial matching of argument names, `h` is sufficient. – Roman Luštrik Mar 03 '18 at 09:00
  • now I already know how to edit and in order to make the code efficient I edit the code to this. myfun2<-function(n1,h1){ r=0 i=0 for (x in n1){ b<-max(0,x+0.85*r) r=b if(r>h1) break i<-i+1 } return(i) } arl=myfun2(ny,0.1865) – jackray Mar 03 '18 at 12:06

2 Answers2

0

@jogo already pointed out the problem. sapply is going through each element of c. Because your example is not fully reproducible it's hard to know what c is but if it's a vector, here's the problem (notice the print statements):

> myfun2 <- function(c1, h1) {
+   r <- rep(0, 500)
+   for (i in 1:499) {
+     print(sprintf("c1[i]: %s, h1: %s, r[i] %s", c1[i], h1, r[i]))
+     r[i + 1] <- max(0, c1[i] + 0.85*r[i])
+     arl <- i
+     if (r[i] > h1) break 
+   }
+   arl
+ }
> 
> set.seed(357)
> c1 <- rnorm(10)
> m <- sapply(c1, h = 0.1865, FUN = myfun2)
[1] "c1[i]: -1.24111730713255, h1: 0.1865, r[i] 0"
[1] "c1[i]: NA, h1: 0.1865, r[i] 0"
[1] "c1[i]: NA, h1: 0.1865, r[i] NA"
Error in if (r[i] > h1) break : missing value where TRUE/FALSE needed
Error during wrapup:
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

now I already know how to edit and in order to make the code efficient I edit the code to this.

myfun2<-function(n1,h1){
  r=0
  i=0
  for (x in n1){
  b<-max(0,x+0.85*r)
  r=b
  if(r>h1) break
    i<-i+1
  }
  return(i)
}
arl=myfun2(ny,0.1865)
jackray
  • 15
  • 6