Reputation: 45
I'm trying to figure out how to add each respective component in a vector and store that in another vector. This is what I have so far:
# Create a function to roll a die n times.
RollDie = function(n) sample(1:6, n, rep=T)
die1 = RollDie(500)
die2 = RollDie(500)
die3 = RollDie(500)
die4 = RollDie(500)
die5 = RollDie(500)
die6 = RollDie(500)
# Sum the values of the first component of each vector which represent the values
# of the six die rolled.
X = sum(die1[1], die2[1], die3[1], die4[1], die5[1], die6[1])
X
What I'm trying to do is sum the first, second, etc components of die 1 through 6.
So, the first component of X will be
sum(die1[1], die2[1], die3[1], die4[1], die5[1], die6[1])
the second component of X will be
sum(die1[2], die2[2], die3[2], die4[2], die5[2], die6[2])
the third component of X will be
sum(die1[3], die2[3], die3[3], die4[3], die5[3], die6[3])
and so on. X will have a length of 500.
I'm trying to find the appropriate command, but not having any luck. Please help. Thanks!
Upvotes: 0
Views: 279
Reputation: 31171
A possible solution with a vectorized approach:
rowSums(replicate(6, RollDie(500)))
Upvotes: 1