谁还没个明天 2011-04-11 11:55 采纳率: 50%
浏览 2981

如何重新排列数据框架中的列?

如何更改此输入(按顺序:时间、输入、输出、文件):

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

转载于:https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame

  • 写回答

10条回答 默认 最新

  • bug^君 2012-07-03 13:20
    关注

    You can also use the subset function:

    data <- subset(data, select=c(3,2,1))
    

    You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

    Update:

    You can also use the select function from the dplyr package:

    data = data %>% select(Time, out, In, Files)
    

    I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

    mtcars %>% select(carb:mpg)
    

    And the following will reorder only some columns, and discard others:

    mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))
    

    Read more about dplyr's select syntax.

    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

问题事件

  • 专家已采纳回答 6月7日

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名