Skip to content
Related Articles

Related Articles

Create Subsets of a Data frame in R Programming – subset() Function
  • Last Updated : 12 Jun, 2020

subset() function in R 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

Example 1:




# 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 selected row from the original data frame.
Example 2:




# 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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :