Select column(s) by position
We can also use the column position and get the column using select() method. Position starts with 1.
Syntax:
select(dataframe,column1_position,column2_position,.,column n_position)
where, dataframe is the input dataframe and column position is an column number
For selecting multiple columns we can use range operator “;” to select columns by their position
Syntax:
select(dataframe,start_position:end_position)
where, dataframe is the input dataframe, start_position is a column number starting position and end_position is a column number ending position
Example 1: R program to select particular column by column position
R
# load the library library (dplyr) # create dataframe with 3 columns # id,name and address data1= data.frame (id= c (1,2,3,4,5,6,7,1,4,2), name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' , 'pinkey' , 'dhanush' , 'sravan' , 'gnanesh' , 'ojaswi' ), address= c ( 'hyd' , 'hyd' , 'ponnur' , 'tenali' , 'vijayawada' , 'vijayawada' , 'guntur' , 'hyd' , 'tenali' , 'hyd' )) # select first column by column position print ( select (data1,1)) # select third column by column position print ( select (data1,3)) |
Output:
Example 2: R program to select multiple columns by positions
R
# load the library library (dplyr) # create dataframe with 3 columns # id,name and address data1= data.frame (id= c (1,2,3,4,5,6,7,1,4,2), name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' , 'pinkey' , 'dhanush' , 'sravan' , 'gnanesh' , 'ojaswi' ), address= c ( 'hyd' , 'hyd' , 'ponnur' , 'tenali' , 'vijayawada' , 'vijayawada' , 'guntur' , 'hyd' , 'tenali' , 'hyd' )) # select multiple column by column position print ( select (data1,1,2)) |
Output:
Example 3: R program to select multiple columns by position with range operator
R
# load the library library (dplyr) # create dataframe with 3 columns # id,name and address data1= data.frame (id= c (1,2,3,4,5,6,7,1,4,2), name= c ( 'sravan' , 'ojaswi' , 'bobby' , 'gnanesh' , 'rohith' , 'pinkey' , 'dhanush' , 'sravan' , 'gnanesh' , 'ojaswi' ), address= c ( 'hyd' , 'hyd' , 'ponnur' , 'tenali' , 'vijayawada' , 'vijayawada' , 'guntur' , 'hyd' , 'tenali' , 'hyd' )) # select multiple column by column # position with : operator print ( select (data1,1:3)) |
Output:
Select variables (columns) in R using Dplyr
In this article, we are going to select variables or columns in R programming language using dplyr library.
Dataset in use:
Contact Us