Hi, I'm learning to write some basic functions in R. For some data I have I'd like to be able to add a variable to itself after each iteration in a for loop to obtain a grandtotal for that variable so I can calculate a mean. test<-function(data){ for (i in 1:80){ meanrotation<-(abs(data[i,3]-data[i,2])+abs(data[i,4]-data[i,2])+abs(data[i,5]-data[i,2])+abs(data[i,6]-data[i,2]))/4 cat(i,meanrotation,"\n") #total+=meanrotation } #print (total/80) } In perl there's an assignment operator variable+=variable2. Is there anything like this in R to do as illustrated in the code above. thanks a lot, Paul Edit - I guess the other way to do this which I just realised is to assign the output of the function to a vector and then do a summary(), but I don't know how to do this either - help is appreciated -- View this message in context: http://www.nabble.com/add-variable-in-for-loop-tp22751641p22751641.html Sent from the R help mailing list archive at Nabble.com.
Hi Paul, you do *not* want to do this, it takes too long and may lead to rounding errors. Vectorize everything, e.g., use sum(meanrotation). And look into ?apply, and google for the "R Inferno". And no, there is no "+="... Good luck! Stephan pgseye schrieb:> Hi, > > I'm learning to write some basic functions in R. For some data I have I'd > like to be able to add a variable to itself after each iteration in a for > loop to obtain a grandtotal for that variable so I can calculate a mean. > > test<-function(data){ > for (i in 1:80){ > > meanrotation<-(abs(data[i,3]-data[i,2])+abs(data[i,4]-data[i,2])+abs(data[i,5]-data[i,2])+abs(data[i,6]-data[i,2]))/4 > cat(i,meanrotation,"\n") > #total+=meanrotation > } > #print (total/80) > } > > In perl there's an assignment operator variable+=variable2. Is there > anything like this in R to do as illustrated in the code above. > > thanks a lot, > > Paul > > Edit - I guess the other way to do this which I just realised is to assign > the output of the function to a vector and then do a summary(), but I don't > know how to do this either - help is appreciated
Seemingly Similar Threads
- MuMIn - assessing variable importance following model averaging, z-stats/p-values or CI?
- obtaining means/SD after fitting a mixed model
- Save object summary to file
- Label 2 groups in PCA different colours
- create a new dataframe with intervals and computing a weighted average for each of its rows