简体   繁体   English

如何找到R中函数列表的总和?

[英]How can i find the sum of a list of functions in R?

So i have a list of functions.I want to create a for loop that returns (obviously as a function) the sum of them. 所以我有一个函数列表。我想创建一个for循环,将其总和返回(显然作为函数)。

In order to create a list of functions inside a for loop i am using this code 为了在for循环中创建函数列表,我正在使用此代码

##CODE

f=dnorm
h=function(x){log(f(x))}

S=c(-3,-2,-1,0,1,2,3)
K=matrix(rep(1:length(S),2),ncol=2)

for(i in 1:length(S)){
   K[i,]=c(S[i],h(S[i]))
  }

funcs=list()

## LOOP TO DEFINE THE LINES

for(i in 1:6){

## Make function name
funcName <- paste( 'hl', i,i+1, sep = '' )

## Make function 
func1 = paste('function(x){  (K[',i,'+1,2]-K[',i,',2])/(K[',i,'+1,1]-K[',i,',1])*x+ 
K[',i,'+1,2]-((K[',i,'+1,2]-K[',i,',2])/(K[',i,'+1,1]-K[',i,',1]))*K[',i,'+1,1]}',sep 
= '')

funcs[[funcName]] = eval(parse(text=func1))

 }

which creates a list of 6 functions. 这将创建6个功能的列表。 How can I get their sum? 我如何获得他们的款项? I tried using the apply commands but either my syntax is not correct or they do not work. 我尝试使用apply命令,但是语法不正确或它们不起作用。

PS I am actually trying to write my one code for the ars command. PS我实际上是在尝试为ars命令编写我的一个代码。

As Nick pointed out, "the sum of functions" doesn't make sense. 正如尼克指出的那样,“功能的总和”是没有意义的。 I'm wildly guessing that you want to evaluate at function at some point (at S ?) and then take the sum of those values. 我在疯狂地猜测,您想在某个时候(在S ?处)对函数求值,然后取这些值的总和。 This should do the trick. 这应该可以解决问题。

rowSums(sapply(funcs, function(f) f(S)))

Much of your code can be written more cleanly, and in a vectorised way. 您的许多代码都可以用矢量化的方式编写得更干净。

f <- dnorm
h <- function(x) log(f(x))

S <- -3:3
K <- cbind(S, h(S))  #No need to define this twice; no need to use a loop 

i <- seq_len(6)
funcNames <- paste('hl', i, i+1, sep = '') #paste is vectorised

#You can avoid using `paste`/`eval`/`parse` with this function to create the functions
#Can possibly be done even more cleanly by using local
makeFunc <- function(i)
{
  evalq(substitute(
    function(x)
    {  
      (K[i + 1, 2] - K[i, 2]) / (K[i + 1, 1] - K[i, 1]) * x + 
      K[i + 1, 2] - 
      ((K[i + 1, 2] - K[i, 2]) / (K[i + 1, 1] - K[i, 1])) * K[i + 1, 1]
    }, 
    list(i = i)
  ))
}

funcs <- lapply(i, makeFunc)
names(funcs) <- funcNames
rowSums(sapply(funcs, function(f) f(S)))

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

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