Take Random Samples from a Data Frame in R Programming – sample_n() Function

sample_n() function in R Language is used to take random sample specimens from a data frame.

Syntax: sample_n(x, n)

Parameters:
x: Data Frame
n: size/number of items to select

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to collect sample data
# from a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
  
# Printing three rows 
sample_n(d, 3

chevron_right


Output:



     name age ht school
1  Chaman   9 NA     no
2    Abhi   7 46    yes
3 Bhavesh   5 NA    yes

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to collect sample data
# from a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
  
# Printing three rows 
sample_n(d, 3, fac = "name")$name

chevron_right


Output:

[1] Chaman  Bhavesh Dimri  
Levels: Abhi Bhavesh Chaman Dimri

Here, in the above code, column name is specified. Hence, the size is applied within the factor.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.