Discalimer: (very inefficient solution see mnel/Gavin's solution)
As you can read the many, many, .. MANY comments underneath each of the answers, while this answer attempts to answer OP's specific question(however inefficient his requirements maybe), in the spirit of maintaining decorum of the forum, some have (rightly) pointed out that the question is in bad taste and my answer doesn't do justice to the forum requirements. I accept all criticism and leave the answer here only for obvious reasons (marked as answer, continuity). I suggest you look at mnel/Gavin's answer for a vectorised solution to this specific problem. If you're interested in looking at an implementation of for-loop, then refer to the bottom of this post, but I suggest you look at it to know the structure of for-loop, but not implement a for-loop to this specific problem. Thank you.
Your code is riddled with quite a few problems, apart from the main problem @Joshua already mentioned:
First, you rewrite every time the values of X and Y inside the loop so, at the end of the loop, there is only the last value of Y that is being summed up.
Second, your code for Y
is not correct. You say, you have to get x
amount of coin tosses, Yet, you use sample(2, 1, ...)
. The 1
must be replaced with X
which equals the number from the die roll.
Try out this code instead:
Youtcomes <- sapply(1:100, function(x) {
X <- sample(1:6, 1, replace=TRUE, rep(1,6)/6)
Y <- sample(c("H", "T"), X, replace=TRUE, rep(1,2)/2)
sum(Y == "T")
})
Here, we loop over 100 times, and each time, sample values between 1 and 6 and store in X. Then, we sample either head
(H) or tail
(T) X
number of times and store in Y.
Now, sum(Y == "T")
gives the sum for current value of x (1 <= x <= 100). So, at the end, Youtcomes
will be your set of simulated Y == Tail
values.
Then, you can do a hist(Youtcomes)
.
Edit: If its a for-loop solution that's desired then,
# always assign the variable you'll index inside for-loop
# else the object will keep growing every time and a copy of
# entire object is made for every i, which makes it extremely
# slow/inefficient.
Youtcomes <- rep(0, 100)
for (i in 1:100) {
X <- sample(1:6, 1, replace=TRUE, rep(1,6)/6)
Y <- sample(c("H", "T"), X, replace=TRUE, rep(1,2)/2)
# assign output inside the loop with [i] indexing
Youtcomes[i] <- sum(Y == "T")
# since Youtcomes is assigned a 100 values of 0's before
# the values will replace 0' at each i. Thus the object
# is not copied every time. This is faster/efficient.
}