Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random element in a list of R?

Tags:

r

a<-c(1,2,0,7,5) 

Some languages have a picker -function -- choose one random number from a -- how in R?

like image 742
hhh Avatar asked Feb 22 '12 07:02

hhh


People also ask

How do I randomly select a vector element in R?

There could be many ways to randomly select elements from an R vector. You can use the sample() or the runif() function to select elements from the vector.

How do you find the random element of a list?

choice, sample, choices) In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple.


2 Answers

# Sample from the vector 'a' 1 element. sample(a, 1) 
like image 180
Dason Avatar answered Sep 23 '22 07:09

Dason


the above answers are technically correct:

sample(a, 1) 

however, if you would like to repeat this process many times, let's say you would like to imitate throwing a dice, then you need to add:

a <- c(1,2,3,4,5,6) sample(a, 12, replace=TRUE) 

Hope it helps.

like image 36
moldovean Avatar answered Sep 21 '22 07:09

moldovean