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:
library(dplyr)
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" ) )
sample_n(d, 3 )
|
Output:
name age ht school
1 Chaman 9 NA no
2 Abhi 7 46 yes
3 Bhavesh 5 NA yes
Example 2:
library(dplyr)
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" ) )
sample_n(d, 3 , fac = "name" )$name
|
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Jun, 2020
Like Article
Save Article