如何在 R 中对数据帧进行排序并保留指定的列顺序?

发布于 2024-10-01 14:58:26 字数 766 浏览 0 评论 0原文

假设我有一个 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

我想按 b 和 c 列对 x 进行排序,但保持 a 的顺序像以前一样。 x[order(x$b, x$c),] - 破坏 a 列的顺序。这就是我想要的:

   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

有没有一种快速的方法?

目前我运行“for”循环并对每个子集进行排序,我确信一定有更好的方法。

谢谢你! 伊利亚

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

骄傲 2024-10-08 14:58:26

如果列“a”已排序,那么就这么简单:

> 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

如果列 a 未排序(但已分组),则创建一个具有 x$a 级别的新因子并使用它。

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.

人疚 2024-10-08 14:58:26

谢谢太空人!你的推荐效果很好。

x$a <- factor(x$a, levels = unique(x$a), ordered = TRUE)
x[order(x$a,x$b, x$c),]

按照加文的评论

   x$a <- factor(x$a, levels = unique(x$a))
   x[order(x$a,x$b, x$c),]

Thank you Spacedman! Your recommendation works well.

x$a <- factor(x$a, levels = unique(x$a), ordered = TRUE)
x[order(x$a,x$b, x$c),]

Following Gavin's comment

   x$a <- factor(x$a, levels = unique(x$a))
   x[order(x$a,x$b, x$c),]
淡淡的优雅 2024-10-08 14:58:26
require(doBy)
orderBy(~ a + b + c, data=x)
require(doBy)
orderBy(~ a + b + c, data=x)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文