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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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