Reputation: 7313
I am trying to create a function that does something like this:
I want "n" to be the number of x's and u's in the function.
For example,
n=3
Myfunction=function(x,n){
assign(paste("u",i,sep=""),x[i])
return(sum(u1+u2+...un))
}
After I create my u1 through u50, how can I call them back so I can sum them i the return function? Using paste("u",i,sep="") makes a new string object, not the formerly created variable.
Thank you for your time and help!
Upvotes: 3
Views: 163
Reputation: 4474
x=1:3
n=3
Myfunction=function(x,n){
for (i in 1:n) assign(paste("u",i,sep=""),x[i])
return(sum(unlist(mget(paste("u",1:n,sep="")))))
}
Myfunction(x,n)
#gives 6
BTW: I assume this is just a minimalistic example of some complexer problem of yours. Otherwise, there would be a much shorter solution for summing up some values, of course. ;)
Upvotes: 1