Switch Two Columns Using Row and Column Syntax

Here we are going to specify a row also separated by a comma.

Syntax:

data[,c("column1", "column2", "column3", "column4",...............)]

where data is the input dataframe

Example:

Exchange 4th column with 6th column

R




# dataframe
data=data.frame(column1=c(1,2,3),
                column2=c(4,5,6),
                column3=c(2,3,4),
                column4=c(4,5,6),
                column5=c(5,3,2),
                column6=c(2,3,1))
  
# display by exchanging 4 th column 
# with 6 th column
data[,c("column1", "column2", "column3",
        "column6","column5","column4")]


Output:



How to Switch Two Columns in R DataFrame?

In this article, we will discuss how to switch two columns in dataframe in R Programming Language.

Let’s create the dataframe with 6 columns

R




# create a dataframe
data = data.frame(column1=c(1, 2, 3), 
                  column2=c(4, 5, 6), 
                  column3=c(2, 3, 4), 
                  column4=c(4, 5, 6), 
                  column5=c(5, 3, 2), 
                  column6=c(2, 3, 1))
  
# display
data


Output:

Similar Reads

Method 1: Using column syntax

...

Method 2: Switch Two Columns Using Row and Column Syntax

Here we have to specify the order of columns....

Contact Us