How to usesample_frac() function in R Language

The sample_frac() function selects a random n percentage of rows from a data frame (or table). First parameter contains the data frame name, the second parameter tells what percentage of rows to select

Syntax:

(sample_frac(dataframe,n)

Where dataframe is the input dataframe and n is the fraction value

Example: R program to filter data using sample_frac() function

R




# load the package
library(dplyr)
  
# create the dataframe with three columns
# id , department and salary with 8 rows
data=data.frame(id=c(7058,7059,7060,7089,7072,7078,7093,7034),
                  
                department=c('IT','sales','finance','IT','finance',
                             'sales','HR','HR'),
                  
                salary=c(34500.00,560890.78,67000.78,25000.00,
                         78900.00,25000.00,45000.00,90000))
  
# display actual  dataframe
print(data)
print("==========================")
  
# return 2 rows
print(sample_frac(data,0.2))
print("==========================")
  
# return 4 rows
print(sample_frac(data,0.4))
print("==========================")
  
# return 7 rows
print(sample_frac(data,0.7))
print("==========================")


Output:



Filter or subsetting rows in R using Dplyr

In this article, we are going to filter the rows from dataframe in R programming language using Dplyr package.

Dataframe in use:

Similar Reads

Method 1: Subset or filter a row using filter()

To filter or subset row we are going to use the filter() function....

Method 2: Filter dataframe with multiple conditions

...

Method 3: Using slice_head() function

We are going to use the filter function to filter the rows. Here we have to specify the condition in the filter function....

Method 4: Using slice_tail() function

...

Method 5: Using top_n() function

...

Method 6: Using slice_sample() function

...

Method 7: Using slice_max() function

This function is used to get top n rows from the dataframe....

Method 8: Using slice_min() function

...

Method 9: Using sample_frac() function

This function is used to get last  n rows from the dataframe...

Contact Us