Choose Specific Columns of a Data Frame in R Programming – select() Function

select() function in R Language is used to choose whether a column of the data frame is selected or not.

Syntax: select(x, expr)

Parameters:
x: Data frame
expr: condition for selection

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to select specific columns
  
# Loading library 
library(dplyr)
    
# Create a data frame
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") ) 
    
# startswith() function to print only ht data 
select(d, starts_with("ht")) 
    
# -startswith() function to 
# print everything except ht data 
select(d, -starts_with("ht")) 

chevron_right


Output:

  ht
1 46
2 NA
3 NA
4 69
     name age school
1    Abhi   7    yes
2 Bhavesh   5    yes
3  Chaman   9     no
4   Dimri  16     no

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to select specific columns
  
# Loading library 
library(dplyr)
    
# Create a data frame
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") ) 
    
# Printing column 1 to 2 
select(d, 1:2
    
# Printing data of column heading containing 'a' 
select(d, contains("a")) 
    
# Printing data of column heading which matches 'na' 
select(d, matches("na")) 

chevron_right


Output:

     name age
1    Abhi   7
2 Bhavesh   5
3  Chaman   9
4   Dimri  16
     name age
1    Abhi   7
2 Bhavesh   5
3  Chaman   9
4   Dimri  16
     name
1    Abhi
2 Bhavesh
3  Chaman
4   Dimri



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.