Using a for in R to generate a table of coin releases

1

Reviewing the exercises for loops of this site

link

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

    
asked by Alejandro Carrera 12.04.2018 в 22:01
source

1 answer

1

The first thing you have tried is correct, but it seems that the if you had outside the cycle. Even to make the code more compact you could use the function ifelse()

x <- c()
for (i in 1:20) {
    x[i] <- ifelse(sample(c(0,1), 1)==0, "head", "tail")
}
table(x)

x
head tail 
  12    8 

This if you want to verify the value in each iteration, but, much more optimal would be, and thanks to ifelse() is a vectorized function, do this:

x <- c()
for (i in 1:20) {
    x[i] <- sample(c(0,1), 1)
}
x <- ifelse(x, "head", "tail")
table(x)

Note, that it is also not really necessary to ask sample(c(0,1), 1)==0 since the automatic coercion of R, the 0 will be "False" and the 1 "True".

It could also be useful to use a Factor from the numeric vector:

x <- c()
for (i in 1:20) {
    x[i] <- sample(c(0,1), 1)
}
x <- factor(x, labels=c("head", "tail"))
table(x)

And finally, you are not obligated that sample return a 1 or a 0 , you could do this:

x <- c()
for (i in 1:20) {
    x[i] <- sample(c("head","tail"), 1)
}
table(x)

Note : I always initialize x by x <- c() simply so as not to have problems between test and test, the author does something similar by coin_outc <- vector(length = n, mode = "integer") just that he already creates it with the size and the appropriate class.

    
answered by 12.04.2018 / 22:52
source