How about:
x <- rnorm(1000) fn <- function(k) sum(x[1:k]*(x[k+1] + x[k+2])) vals <- sapply(1:100, fn) vals -------------------------------------- Jonathan P. Daily Technician - USGS Leetown Science Center 11649 Leetown Road Kearneysville WV, 25430 (304) 724-4480 "Is the room still a room when its empty? Does the room, the thing itself have purpose? Or do we, what's the word... imbue it." - Jubal Early, Firefly r-help-boun...@r-project.org wrote on 03/10/2011 08:49:25 AM: > [image removed] > > [R] sum of variables in function > > beatleb > > to: > > r-help > > 03/10/2011 01:15 PM > > Sent by: > > r-help-boun...@r-project.org > > 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. ______________________________________________ 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.