function with loop in r -


i having trouble getting following function work. simplification of function have use.

data example:

x = c(1628.584,2071.944,3365.916, 6450.724) n = length(x) r = seq(0.1,0.5,by=0.1) q = seq(0,2,by=1) 

then write function has used in next function:

 gh <- function(r,q){     ifelse(r>0 & p>1, r*p,            ifelse(r>0 & p==1, q+1-r, na))   }  

what want next function is:

# p=1 # d <- (log(x[p])/log(n^(-1))-outer(r,q,gh))^2 # p=2 # f <- (log(x[p])/log(n^(-1))-outer(r,q,gh))^2 # p=3  # g <- (log(x[p])/log(n^(-1))-outer(r,q,gh))^2 # p=4 # k <- (log(x[p])/log(n^(-1))-outer(r,q,gh))^2 # # z <- d+f+g+k 

therefore, write:

ws <- function(r,q){   we=0   for(p in seq(from=1,to=4, by=1)){     we= we+ (log(x[p])/log(n^(-1))-outer(r,q,gh))^2   }   return(we) }  o <-ws(r,q) 

but error:

error in ifelse(r > 0 & p > 1, r * p, ifelse(r > 0 & p == 1, q + 1 - r,  :                                                   object 'p' not found  

this having trouble understanding, because looping on "p" ?

from ?outer:

outer(x, y, fun = "*", ...)

... optional arguments passed to

so , can add parameter p function :

gh <- function(r,q,p){   ifelse(r>0 & p>1, r*p,          ifelse(r>0 & p==1, q+1-r, na)) }  

then call using ... argument:

outer(r,q,gh,p=1)      [,1] [,2] [,3] [1,]  0.9  1.9  2.9 [2,]  0.8  1.8  2.8 [3,]  0.7  1.7  2.7 [4,]  0.6  1.6  2.6 [5,]  0.5  1.5  2.5 

in loop call it:

 outer(r,q,gh,p=p) 

that's said pretty sure not need use for here.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -