简体   繁体   中英

Summing elements of a vector in R

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!

向量化方法的可能解决方案:

rowSums(replicate(6, RollDie(500)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM