Reputation: 1
I need to repeat the following a process like this 10 times:
> random=rnorm(5)
> total=sum(random)
and then put the total each time into a vector called final.
For a loop I guess I would write:
> final <- c(total[[i]])
> for(i in 1:10){
random=rnorm(5)
total=sum(random)
...
}
...not sure how to put my totals into my final vector? Also from looking around online most places say I should use an apply code. Which should I use and how can I put the totals into final?
Upvotes: 0
Views: 301
Reputation: 7248
R provides a function called replicate
for exactly this use case, it will repeat the operation as many times as you specify, and store the results in a vector:
> replicate(10, sum(rnorm(5)))
[1] -0.2286870 1.5123902 -5.8179539 1.2119908 -2.8749987 5.5817021
[7] 2.5427969 2.1833426 0.4884455 -3.6787912
If the function to produce data is more complex, then you can either use replicate to invoke a function, or use sapply directly. So
> genRandomData <- function() {
random <- rnorm(100)
c(sum(random), var(random))
}
> replicate(10, genRandomData())
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 6.612235 6.895032 -4.004501 -8.250871 2.3098680 2.0388161 23.5202949
[2,] 1.082576 0.769107 1.119480 1.206932 0.9930102 0.9078762 0.9544335
[,8] [,9] [,10]
[1,] -12.2080648 9.0074524 0.2358715
[2,] 0.8256081 0.8669045 0.9017415
or, to produce the same output using sapply (which is nice because it doesn't reply on substitution),
> sapply(integer(10), function(x) {
random <- rnorm(100)
c(sum(random),var(random))
})
If you want to get a data frame out of the end of this, you have to transpose; so
> data.frame(t(sapply(integer(10), function(x) {
random <- rnorm(100)
list(s=sum(random),v=var(random))
})))
s v
1 -6.343845 1.0397
2 12.94773 0.9480807
3 5.811322 0.9670198
4 -1.941444 1.04547
5 -0.9094589 0.862759
6 -2.852641 0.5504582
7 -8.471266 1.080554
8 -17.2341 1.201679
9 11.60805 1.150254
10 -7.138314 1.080731
Upvotes: 2