简体   繁体   中英

sapply or other apply function in R

I wrote some code yesterday and it was confusing you to help. Sorry about that. So I wrote it again in an easier way.

My question is: is there easier (or faster) way to implement the following code?

k <- c(.04, .08, .12, .16, .2);

library(plyr)
valfcn <- function(k, V_next){
  a <- .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 like to use alternative way which might be shorter but faster, instead of using the for-loop method.

Best!

I believe the sapply() isn't necessary based on your description. Something like this might do what you're looking for:

valfcn <- function(k, V_next){
  a <- .3;
  b <- .6;
  max(log(k^a - k) + b*V_next);
}

In this version, the transformation being done to k produces a vector and then max() operates on the entire vector. No need to use a loop or use sapply() , since max() takes care of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM