+5 votes
in Programming Languages by (40.5k points)
I want to randomly select k elements from a large R vector without knowing their indices. What R function should I use for it?

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

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.

Here is an example to show how to use these functions. I am selecting 5 elements in this example.

> a <- c(11,10,18,12,21,35,40,91,32,33,34,45,46,47,61,62,63,64,65,83,81)
> k=5
> sample(a,k)
[1] 83 32 62 45 47
> i= runif(k, min=1, max=length(a))
> i
[1] 16.860194  8.193600 15.902176 16.875151  8.351928
> i= floor(runif(k, min=1, max=length(a)))
> a[i]
[1] 62 34 12 62 83

Related questions

+4 votes
1 answer
+5 votes
1 answer
+4 votes
1 answer

...