Move Column to First Position of DataFrame in R
In this article, we are going to see how to move particular column in the dataframe to the first position of the dataframe in R Programming language.
Create dataframe for demonstration:
R
data = data.frame (id= c (1, 2, 3),
name= c ( "sravan" , "bobby" ,
"satwik" ),
age= c (23, 21, 17),
address= c ( "kakumanu" , "ponnur" , "hyd" ))
data
|
Output:
Method 1: Using Base R
In this method we will move the columns to the first position using base R language.
Syntax: dataframe[ , c(“column_name”, names(dataframe)[names(dataframe) != “column_name”])]
where
- dataframe is the input dataframe
- column_name is the name of the column to be shifted to the first
We are going to move a particular column to first position using index operator and by c() function, we will combine the column name and then pushed to first position in the dataframe.
Example: R program to shift the columns to first for the above-created dataframe.
R
data = data.frame (id = c (1,2,3),
name = c ( "sravan" , "bobby" ,
"satwik" ),
age = c (23,21,17),
address = c ( "kakumanu" , "ponnur" , "hyd" ))
print ( "Original Dataframe" )
data
print ( "After moving age to first column : " )
data_Sorted = data[ , c ( "age" ,
names (data)[ names (data) != "age" ])]
data_Sorted
print ( "After move address to first column : " )
data_Sorted1 = data[ , c ( "address" ,
names (data)[ names (data) != "address" ])]
data_Sorted1
|
Output:
Method 2 : Using dplyr() package
By using this package we can shift particular column to the first, Here we are using %>% operator to load the shifted data into dataframe and use the select () function that takes the particular column name to be shifted and every() thing is used to get the dataframe data
Syntax: dataframe%>% dplyr::select(“column_name”, everything())
where
- dataframe is the input dataframe
- column_name is the column to be shifted to first
Example: R program to shift particular column to first
R
library ( "dplyr" )
data = data.frame (id = c (1,2,3),
name = c ( "sravan" , "bobby" ,
"satwik" ),
age = c (23,21,17),
address = c ( "kakumanu" , "ponnur" , "hyd" ))
print ( "Original Dataframe" )
data
print ( "After moving age to first column : " )
data_Sorted = data %>% dplyr:: select ( "age" ,
everything ())
data_Sorted
|
Output:
Last Updated :
23 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...