![]() |
VOOZH | about |
In this article, we are going to select variables or columns in R programming language using dplyr library.
Dataset in use:
👁 ImageHere we will use select() method to select column by its name
Syntax:
select(dataframe,column1,column2,.,column n)
Here, data frame is the input dataframe and columns are the columns in the dataframe to be displayed
Example 1: R program to select columns
Output:
👁 ImageExample 2: R program to select multiple columns
Output:
👁 ImageWe 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
Output:
👁 ImageExample 2: R program to select multiple columns by positions
Output:
👁 ImageExample 3: R program to select multiple columns by position with range operator
Output:
👁 ImageHere, we will display the column values based on values or pattern present in the column
Display the column that contains the given sub string
Syntax:
select(dataframe,contains('sub_string'))
Here, dataframe is the input dataframe and sub_string is the string present in the column name
Example: R program to select column based on substring
Output:
👁 ImageIt will check and display the column that contains the given sub string
select(dataframe,matches('sub_string'))
Here, dataframe is the input dataframe and sub_string is the string present in the column name
Example: R program to select column based on substring
Output:
👁 ImageHere we can also select columns based on starting and ending characters.
Syntax:
select(dataframe,starts_with('substring'))
Where, dataframe is the input dataframe and substring is the character/string that starts with it
Syntax:
select(dataframe,ends_with('substring'))
where, dataframe is the input dataframe and substring is the character/string that ends with it
Example 1: R program to display columns that starts with a character/substring
Output:
👁 ImageExample 2: R program to select column that ends with a given string or character
Output:
👁 ImageWe can select all the columns in the data frame by using everything() method.
Syntax:
select(dataframe,everything())
Example: R program to select all columns
Output:
👁 Image