如何使用指定的列顺序保存对R中的数据框进行排序? [英] How to sort dataframe in R with specified column order preservation?
本文介绍了如何使用指定的列顺序保存对R中的数据框进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x< - data.frame(a = c('A' ,'A','A','A','A','C','C','C','C','B','B','B'),
b = c('a','c','a','a','c','d','e','e','d','b','b' ),
c = c(7,3,2,4,5,3,1,1,5,5,2,3),
stringsAsFactors = FALSE)
> x
abc
1 A a 7
2 A c 3
3 A a 2
4 A a 4
5 A c 5
6 C d 3
7 C e 1
8 C e 1
9 C d 5
10 B b 5
11 B b $ 2
12 B b 3
我想按列b和c排序x,但按照以前的顺序排列。 x [order(x $ b,x $ c),]
- 打破列a的顺序。这是我想要的:
abc
3 A a 2
4 A a 4
1 A a 7
2 A c 3
5 A c 5
6 C d 3
9 C d 5
7 C e 1
8 C e 1
11 B b 2
12 B b 3
10 B b 5
有快速的做法吗?
目前,我运行for循环并排序每个子集,我相信必须有一个更好的方法。
谢谢!
Ilya
解决方案
如果列a已经订购,那么这个简单:
> x [order(x $ a,x $ b,x $ c),]
abc
3 A a 2
4 A a 4
1 A a 7
2 A c 3
5 A c 5
6 B d 3
9 B d 5
7 B e 1
8 B e 1
11 C b 2
12 C b 3
10 C b 5
如果列a没有订购(但被分组),创建一个新的因子,级别为x $ a并使用它。
Let's say I have a data.frame
x <- data.frame(a = c('A','A','A','A','A', 'C','C','C','C', 'B','B','B'),
b = c('a','c','a','a','c', 'd', 'e','e','d', 'b','b','b'),
c = c( 7, 3, 2, 4, 5, 3, 1, 1, 5, 5, 2, 3),
stringsAsFactors = FALSE)
> x
a b c
1 A a 7
2 A c 3
3 A a 2
4 A a 4
5 A c 5
6 C d 3
7 C e 1
8 C e 1
9 C d 5
10 B b 5
11 B b 2
12 B b 3
I would like to sort x by columns b and c but keeping order of a as before. x[order(x$b, x$c),]
- breaks order of column a. This is what I want:
a b c
3 A a 2
4 A a 4
1 A a 7
2 A c 3
5 A c 5
6 C d 3
9 C d 5
7 C e 1
8 C e 1
11 B b 2
12 B b 3
10 B b 5
Is there a quick way of doing it?
Currently I run "for" loop and sort each subset, I'm sure there must be a better way.
Thank you! Ilya
解决方案
If column "a" is ordered already, then its this simple:
> x[order(x$a,x$b, x$c),]
a b c
3 A a 2
4 A a 4
1 A a 7
2 A c 3
5 A c 5
6 B d 3
9 B d 5
7 B e 1
8 B e 1
11 C b 2
12 C b 3
10 C b 5
If column a isn't ordered (but is grouped), create a new factor with the levels of x$a and use that.
这篇关于如何使用指定的列顺序保存对R中的数据框进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文