如何改变这个输入(顺序:时间,输入,输出,文件):

Time   In    Out  Files
1      2     3    4
2      3     4    5

到这个输出(序列:时间,输出,输入,文件)?

Time   Out   In  Files
1      3     2    4
2      4     3    5

这是虚拟R数据:

table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
##  Time In Out Files
##1    1  2   3     4
##2    2  3   4     5

当前回答

# reorder by column name
data <- data[, c("A", "B", "C")] # leave the row index blank to keep all rows

#reorder by column index
data <- data[, c(1,3,2)] # leave the row index blank to keep all rows

其他回答

你的数据帧有四列,比如df[,c(1,2,3,4)]。 注意,第一个逗号表示保留所有行,1、2、3、4表示列。

要像上面的问题一样改变顺序,请执行df2[,c(1,3,2,4)]

如果你想以csv格式输出这个文件,请执行write.csv(df2, file="somedf.csv")

Dplyr 1.0.0版本包含了relocate()函数来轻松地重新排序列:

dat <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))

library(dplyr) # from version 1.0.0 only

dat %>%
  relocate(Out, .before = In)

or

dat %>%
  relocate(Out, .after = Time)
# reorder by column name
data <- data[, c("A", "B", "C")] # leave the row index blank to keep all rows

#reorder by column index
data <- data[, c(1,3,2)] # leave the row index blank to keep all rows

你可以使用数据。表包:

如何重新排序数据。表列(不复制)

require(data.table)
setcolorder(DT,myOrder)

我唯一见过的效果不错的就是这里。

 shuffle_columns <- function (invec, movecommand) {
      movecommand <- lapply(strsplit(strsplit(movecommand, ";")[[1]],
                                 ",|\\s+"), function(x) x[x != ""])
  movelist <- lapply(movecommand, function(x) {
    Where <- x[which(x %in% c("before", "after", "first",
                              "last")):length(x)]
    ToMove <- setdiff(x, Where)
    list(ToMove, Where)
  })
  myVec <- invec
  for (i in seq_along(movelist)) {
    temp <- setdiff(myVec, movelist[[i]][[1]])
    A <- movelist[[i]][[2]][1]
    if (A %in% c("before", "after")) {
      ba <- movelist[[i]][[2]][2]
      if (A == "before") {
        after <- match(ba, temp) - 1
      }
      else if (A == "after") {
        after <- match(ba, temp)
      }
    }
    else if (A == "first") {
      after <- 0
    }
    else if (A == "last") {
      after <- length(myVec)
    }
    myVec <- append(temp, values = movelist[[i]][[1]], after = after)
  }
  myVec
}

像这样使用:

new_df <- iris[shuffle_columns(names(iris), "Sepal.Width before Sepal.Length")]

效果非常好。