What does the following line on R do?

Asked

Viewed 72 times

-3

I’m having second thoughts about the following line:

 amostra = sample(2,40,replace = T,prob=c(0.7,0.3))?

In particular the argument 2, the argument 40 and the replace.

1 answer

5

The syntax the way it is is a little weird.

As described in the documentation, the first argument can be an array, from which you want to take a display or an integer number. If it’s an integer, she’ll make a sample of 1 up to that number. In the case, since it is an integer number (2), the function will make a sample of the vector c(1,2).

40, the second argument (n), is the size of the sample you want to pull out. That is, this function call sample will return a vector with 40 elements.

replace is an argument whether the sample will be made with or without replacement. In case, as you will make a size 40 sample of a size 2 vector, it is obligatory with replacement (replace = TRUE).

Finally, the argument prob allows you to specify probabilities to draw each of the vector elements you are sampling. In the case, c(0.7, 0.3) indicates that in the call of this function you will go 1 with 70% probability and 2 with 30%.

To summarize: This line returns a random sample with size reset 40 of the vector elements c(1,2) where 1 has probability 70% and 2, 30%.


In the R, in general the documentation is reasonably good. It is worth reading the help of the functions. Inside the R itself, if you type help(sample), a window will appear with the documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.