Sample function in R, generates a sample of the specified size from the data set or elements, either with or without replacement.
Syntax for Sample Function in R:
|x||Data Set or a vector of one or more elements from which sample is to be chosen|
|size||size of a sample|
|replace||Should sampling be with replacement?|
|prob||probability weights for obtaining the elements of the vector being sampled|
Sample function in R with replacement:
Lets see an example that genereates 10 random sample from vector of 1 to 20. With replacement =TRUE. which means value in the sample can occur more than once
## basic Sample function in R sample(1:20, 10, replace=TRUE)
When we run the above code the output will be
Sample Function in R with set.seed():
If we run the sample function again and again, it gives different set of samples each time.What if we require the same sample each time?
For that we use set.seed() function. Set.seed() function always returns the same pseudo-random sequence.
## Sample function in R with set.seed() set.seed(10) sample(1:20, 10, replace=TRUE)
Whenever we run the sample function along with the set.seed() function it outputs same set of samples.
so the output always will be the same for set.seed(10)
Sample function in R with no Replacement:
By passing an argument replace = FALSE. We can draw a sample without replacement
## Sample function in R with No Replacement sample(1:20, 10, replace=FALSE)
so the output will be without any repetition
Sample Function in R with dataset:
Let’s extract set of sample elements from the data set with the help of sample function in R. We will use default mtcars table in r
## applying Sample function in R to mt cars table to extract 5 sample rows set.seed(123) index<-sample(1:nrow(mtcars), 5) index mtcars[index,]
when we execute the above code ·
- sample function returns the 5 row indexes to the index object·
- Then that 5 indexes are passed as input to the mtcars to fetch that 5 rows
So the output will be
mpg cyl disp hp drat wt qsec vs am gear carb
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
As we have set seeds it will give the same set of 5 rows as a sample.