Reordering the columns in a data frame

本文介绍如何使用R语言重新排列数据框中的列顺序。包括按列号和列名两种方式,并提供具体示例。

Problem

You want to do reorder the columns in a data frame.

Solution

# A sample data frame
data <- read.table(header=TRUE, text='
    id weight   size
     1     20  small
     2     27  large
     3     24 medium
')

# Reorder by column number
data[c(1,3,2)] #> id size weight #> 1 1 small 20 #> 2 2 large 27 #> 3 3 medium 24 # To actually change `data`, you need to save it back into `data`: # data <- data[c(1,3,2)] # Reorder by column name data[c("size", "id", "weight")] #> size id weight #> 1 small 1 20 #> 2 large 2 27 #> 3 medium 3 24 

 

REF:

http://www.cookbook-r.com/Manipulating_data/Reordering_the_columns_in_a_data_frame/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值