Hi: Assuming that z constitutes the last two elements of your input vector,
try2 <- function(x) { n <- length(x) y <- x[1:(n - 2)] z <- x[n - 1] + x[n] sum(y) * z } x0 <- 1:4 # result should be 21 x1 <- 1:8 # z = 15, result = 21 * 15 = 315 try2(x0) try2(x1) HTH, Dennis On Thu, Mar 10, 2011 at 5:49 AM, beatleb <rhelpfo...@gmail.com> wrote: > Dear R users, > > Probably, this is quite a simpe question, but I do not find the proper way > to obtain want I need. To explain the problem, I constructed a simple > example. > > Suppose I have the following function: > > try1<-function(x){ > y<-x[1:2] > z<-x[3:4] > y[1]*(z[1]+z[2])+y[2]*(z[1]+z[2]) > } > > This function will be part of a for loop. This is what I like to obtain for > every k: > > if k=2 > try1<-function(x){ > y<-x[1:2] > z<-x[3:4] > y[1]*(z[1]+z[2])+y[2]*(z[1]+z[2]) > } > > if k=3 > try1<-function(x){ > y<-x[1:3] > z<-x[4:5] > y[1]*(z[1]+z[2])+y[2]*(z[1]+z[2])+y[3]*(z[1]+z[2]) > } > > if k=4 > try1<-function(x){ > y<-x[1:3] > z<-x[4:5] > y[1]*(z[1]+z[2])+y[2]*(z[1]+z[2])+y[3]*(z[1]+z[2])+y[4]*(z[1]+z[2]) > } > > Assume that k will be quite high, for example 100. > The problem isn't in defining a for loop, or in defining the appropriate y > or z, but in the line starting with > y[1]. The values of the variables are still unknown, which causes that I am > not able to create this sum. > > I really hope that there is somebody in the audience that can help me. > > > > -- > View this message in context: > http://r.789695.n4.nabble.com/sum-of-variables-in-function-tp3345888p3345888.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.