I'm having trouble performing the following computations in RMarkdown. I'm new to this program and have the R for Everyone book, but still can't get the right output. I would be very grateful if a master could assist.
Suppose you role a die twice in succession, getting X1 and X2. Then divide them, getting Y=X1X2. Thus, Y
is discrete, ranging from a minimum of 1/6 to a maximum of 6.
X1 = c(1,2,3,4,5,6)
X2 = c(1,2,3,4,5,6)
Y = c()
for (i in X1) {
for (j in X2) {
Y = c(Y, i/j)
}
}
This looks like it may be a homework problem, so instead of writing out the code for you, I'll try to explain where you've gone astray in thinking about your code.
When you write for (i in X1), you are instructing i to iterate over the values in X1. So i will take on the values 1, 2, 3, 4, 5, and 6. j will do likewise, and so your loop will iterate exactly 36 times. As it is written, your loop cannot iterate 10000 times.
Thus, you may want to iterate over something other than X1 and X2.
My hint would be to use the following code
Y <- vector("numeric", 10000)
This assigns a vector of 10000 values to Y. Each value starts at zero, but can be replaced, with an expression of Y[i] <- ... where i is the element to be replaced. In a for loop, you can iterate over the length of Y with for (i in seq_along(Y))
Lastly, in order to simulate your dice, you can succinctly simulate the ratio of X1 to X2 with
sample(1:6, 1) / sample(1:6, 1)
If you can do that 10000 times and assign it to Y, you'll be on your way to a solution.
This question seems to be about using the R language, not specifically about using R Markdown (a system for mixing code with text to produce reports in different formats), so I am changing the category to #general.
Also, for the benefit of future readers… Before posting classwork/homework questions here, please read our Homework Policy. The key bits:
Clearly state that your post is class-related
Don't post verbatim text from assignments or problem sets
Show the work you've already done and don't expect anyone to solve the whole problem for you
I answered this question in two ways, a & b. The first was the mean Y of a random sample of X1 and X2. Then, I calculated the weighted sum of the random variables shown in the figure before finding Y.
I understand. I've already posted my solutions. I should reword it to show the need for a larger sample size and how to simplify the 10,000 ratios after the weighted probabilities.
FYI, you can edit your own posts — look for the little grey pencil icon at the bottom of each post. But don't edit your original post in a way that makes the later conversation confusing to follow. (it's better to add updates than to totally replace stuff that was already responded to)
Does anyone know a quick code to use to calculate the 10,000 probabilities ratio? All I'm getting is a giant list and confusion on what code/equation to use.
p.die <- rep(1/6,6)
sum(p.die)
die <- 1:6
sample(die, size=10000, prob=p.die, replace=T)