简体   繁体   English

R中的sapply或其他apply函数

[英]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. 我想使用替代方法,它可能更短但更快,而不是使用for循环方法。

Best! 最好!

I believe the sapply() isn't necessary based on your description. 我相信sapply()根据您的描述不是必需的。 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. 在此版本中,对k进行的转换将生成一个向量,然后max()整个向量进行运算。 No need to use a loop or use sapply() , since max() takes care of it. 不需要使用循环或使用sapply() ,因为max()会处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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