Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Create Subsets of a Data frame in R Programming – subset() Function

  • Last Updated : 22 Nov, 2021

subset() function in R Programming Language is used to create subsets of a Data frame. This can also be used to drop columns from a data frame.

Syntax: subset(df, expr)

Parameters: 

  • df: Data frame used
  • expr: Condition for subset

Create Subsets of Data frame in R Programming Language

Here we will make subsets of dataframe using subset() methods in R language.

Example 1: Basic example of R – subset() Function

R




# R program to create
# subset of a data frame
   
# Creating a Data Frame
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print ("Original Data Frame")
print (df)
   
# Creating a Subset
df1<-subset(df, select = row2)
print("Modified Data Frame")
print(df1)

Output: 

[1] "Original Data Frame"
  row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8
[1] "Modified Data Frame"
  row2
1    3
2    4
3    5

Here, in the above code, the original data frame remains intact while another subset of data frame is created which holds a selected row from the original data frame. 

Example 2: Create Subsets of Data frame in R Language

Python3




# R program to create
# subset of a data frame
   
# Creating a Data Frame
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print ("Original Data Frame")
print (df)
   
# Creating a Subset
df<-subset(df, select = -c(row2, row3))
print("Modified Data Frame")
print(df)

Output: 

[1] "Original Data Frame"
  row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8
[1] "Modified Data Frame"
  row1
1    0
2    1
3    2

Here, in the above code, the rows are permanently deleted from the original data frame.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!