Reviewing the exercises for loops of this site
I was curious about number 5: "Use a for loop to simulate 20 coin tosses 20 times, recording the results (1 = heads, 0 = tails) in a pre-set vector" (own translation)
The solution proposed by the author is this
n <- 20
coin_outc <- vector(length = n, mode = "integer")
for (i in 1:20) {
coin_outc[i] <- sample(c(0L, 1L), 1)
}
coin_outc
## [1] 0 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0
Although I was able to get a similar approach with
for (i in 1:20) {
x[i] <- sample(c(0,1), 1)
}
table(x)
x
0 1
11 9
##Ojo: El número de 0 y 1 varía por cada llamada al loop.
That also generates the frequency table.
Now, I want to go a little further so that, instead of only reporting the frequency of 0 and 1, the table indicates the number of heads and tails, but with the names, that is something like:
x
tails heads
11 9
I've tried things like
for (i in 1:20) {
x[i] <- sample(c(0,1), 1)
}
if (x[i] == 0) {
i <- "head"
} else {
i <- "tail"
}
table(x)
Or this
for (i in 1:20) {
x[i] <- sample(c(0,1), 1)
}
for (i in x) {
if (i==0) {
print("heads")
} else {
print("tails")
}
}
table(x)
What results (I omitted some lines)
[1] "heads"
[1] "tails"
[1] "tails"
[1] "tails"
[1] "heads"
[1] "tails"
[1] "heads"
[1] "heads"
> table(x)
x
0 1
14 6
Any suggestions on how to achieve the desired result? My interest is that it can be done from a for, not using some other method. Thanks in advance