for loop - sapply or other apply function in R -
for loop - sapply or other apply function in R -
i wrote code yesterday , confusing help. sorry that. wrote 1 time again in easier way.
my question is: there easier (or faster) way implement next code?
k <- c(.04, .08, .12, .16, .2); library(plyr) valfcn <- function(k, v_next){ <- .3; b <- .6; return_val <- vector() for(i in 1:5){ tmp <- vector() for(j in 1:5){ tmp[j] <- (log(k[i]^a - k[j]) + b*v_next[j]); } return_val <- c(return_val,max(tmp[i])) } return_val } v0 <- c(rep(0,5)) v1 <- valfcn(k,v0) v2 <- valfcn(k,v1) v1 v2 i'd utilize alternative way might shorter faster, instead of using for-loop method.
best!
i believe sapply() isn't necessary based on description. might you're looking for:
valfcn <- function(k, v_next){ <- .3; b <- .6; max(log(k^a - k) + b*v_next); } in version, transformation beingness done k produces vector , max() operates on entire vector. no need utilize loop or utilize sapply(), since max() takes care of it.
r for-loop
Comments
Post a Comment