简体   繁体   中英

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.

In order to create a list of functions inside a for loop i am using this code

##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. How can I get their sum? I tried using the apply commands but either my syntax is not correct or they do not work.

PS I am actually trying to write my one code for the ars command.

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. 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)))

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