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




# load the dplyr package
library("dplyr")
  
# create a dataframe with 4 columns
# they are id,name,age and address
  
data = data.frame(id = c(1,2,3),
                  name = c("sravan","bobby",
                           "satwik"),
                  age = c(23,21,17),
                  address = c("kakumanu","ponnur","hyd"))
  
# display
print("Original Dataframe")
data
  
print("After moving age to first column : ")
  
# move age to first column
data_Sorted = data %>% dplyr::select("age"
                                     everything())
  
# display sorted data
data_Sorted


Output:



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




# create a dataframe with 4 columns
# they are id,name,age and address
data = data.frame(id=c(1, 2, 3),
                  name=c("sravan", "bobby",
                         "satwik"),
                  age=c(23, 21, 17),
                  address=c("kakumanu", "ponnur", "hyd"))
  
# display
data


Output:

Similar Reads

Method 1: Using Base R

...

Method 2 : Using dplyr() package

In this method we will move the columns to the first position using base R language....

Contact Us