开发者

Reordering and reshaping columns in R [duplicate]

开发者 https://www.devze.com 2023-03-29 23:19 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to sort a dataframe by column(s) in R
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to sort a dataframe by column(s) in R

I have a dataset that looks like this:

x       y     z
1.    开发者_运维百科  1     0.2
1.1     1     1.5
1.2     1     3.
1.      2     8.1
1.1     2     1.0
1.2     2     0.6

What I would like is organise the dataset first as a function of x in increasing order then as a function of y such that

x       y      z 
1.      1      0.2
1.      2      8.1
1.1     1      1.5
1.1     2      1.
1.2     1      3.
1.2     2      0.6

I know that apply, mapply, tapply, etc functions reorganise datasets but I must admit that I don't really understand the differences between them nor do I really understand how to apply which and when.

Thank you for your suggestions.


You can order your data using the order function. There is no need for any apply family function.

Assuming your data is in a data.frame called df:

df[order(df$x, df$y), ]
    x y   z
1 1.0 1 0.2
4 1.0 2 8.1
2 1.1 1 1.5
5 1.1 2 1.0
3 1.2 1 3.0
6 1.2 2 0.6

See ?order for more help.


On a side note: reshaping in general refers to changing the shape of a data.frame, e.g. converting it from wide to tall format. This is not what is required here.


You can also use the arrange() function in plyr for this. Wrap the variables in desc() that you want to sort the other direction.

> library(plyr)
> dat <- head(ChickWeight)
> arrange(dat,weight,Time)
  weight Time Chick Diet
1     42    0     1    1
2     51    2     1    1
3     59    4     1    1
4     64    6     1    1
5     76    8     1    1
6     93   10     1    1

This is the fastest way to do this that's still readable, if speed matters in your application. Benchmarks here: How to sort a dataframe by column(s)?

0

精彩评论

暂无评论...
验证码 换一张
取 消