[R] error in self-made function - cannot deal with objects of length = 1
R. Michael Weylandt <michael.weylandt@gmail.com>
michael.weylandt at gmail.com
Mon Aug 1 22:07:44 CEST 2011
Just jumping into this, but does the ROC(x, type="discrete") function of either the TTR or caTools (can't remember which) work if you need a prebuilt function?
Also, why are you dividing by the max value? That seems a funny way to calculate ROC...
On Aug 1, 2011, at 3:14 PM, bjmjarrett <bjmjarrett at gmail.com> wrote:
> I have a function to calculate the rate of increase (the difference between
> the value and the previous value divided by the total number of eggs in a
> year) of egg production over the course of a year:
>
> rate <- function(x){
> storage <- matrix(nrow=length(x),ncol=1)
> storage[1,] <- x[1] / max(x) # as there is no previous value
> for( i in 2:length(x)){
> p <- i - 1
> storage[i,] <- ((x[i] - x[p] / max(x))
> }
> return(storage)
> }
>
> However, as it requires the subtraction of one term with the previous term
> it fails when dealing with objects with length = 1 (when only one reading
> has been taken in a year). I have tried adding an ifelse() function into
> `rate' with NA added for length 1:
>
> rate <- function(x){
> storage <- matrix(nrow=length(x),ncol=1)
> ifelse(length(x)==1,storage[1,] <- NA,{
> storage[1,] <- x[1]/max(x)
> for(i in 2:length(x)){
> p <- i-1
> storage[i,] <- ((x[i] - x[p]) / max(x))
> }
> })
> return(storage)
> }
>
> but I end up with this error when I try and use the above function in
> tapply():
>
> Error in ans[!test & !nas] <- rep(no, length.out = length(ans))[!test & :
> replacement has length zero
>
> Thanks in advance,
>
> Ben
>
> --
> View this message in context: http://r.789695.n4.nabble.com/error-in-self-made-function-cannot-deal-with-objects-of-length-1-tp3710555p3710555.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list