📜  如何在 R DataFrame 中切换两列?

📅  最后修改于: 2022-05-13 01:55:48.142000             🧑  作者: Mango

如何在 R DataFrame 中切换两列?

在本文中,我们将讨论如何在 R 编程语言中切换 dataframe 中的两列。

让我们创建 6 列的数据框

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


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 first column 
# with 5th column
data[c("column5", "column2", "column3",
       "column4", "column1", "column6")]


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")]


输出

方法一:使用列语法

在这里,我们必须指定列的顺序。

语法

data

其中 data 是输入数据框

示例

将第 1与第 5交换。

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 first column 
# with 5th column
data[c("column5", "column2", "column3",
       "column4", "column1", "column6")]

输出

方法 2:使用行列语法切换两列

在这里,我们将指定一个也用逗号分隔的行。

语法

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

其中 data 是输入数据框

示例

将第 4与第 6交换

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")]

输出