8

What is a good way to perform the following task?

I have a data frame, for example:

v2 <- c(4.5, 2.5, 3.5, 5.5, 7.5, 6.5, 2.5, 1.5, 3.5)
v1 <- c(2.2, 3.2, 1.2, 4.2, 2.2, 3.2, 2.2, 1.2, 5.2)
lvl <- c("a","a","a","b","b","b","c","c","c")
d <- data.frame(v1,v2,lvl)

> d
   v1  v2 l
1 2.2 4.5 a
2 3.2 2.5 a
3 1.2 3.5 a
4 4.2 5.5 b
5 2.2 7.5 b
6 3.2 6.5 b
7 2.2 2.5 c
8 1.2 1.5 c
9 5.2 3.5 c

Within each level of d$lvl, I want to sort the data frame by value of d$v1. So I want to get

   v1  v2 l
3 1.2 3.5 a
1 2.2 4.5 a
2 3.2 2.5 a

5 2.2 7.5 b
6 3.2 6.5 b
4 4.2 5.5 b

8 1.2 1.5 c
7 2.2 2.5 c
9 5.2 3.5 c
4

3 回答 3

12

我认为最直接的方法是

d[order(d$lvl,d$v1),]

这使

   v1  v2 lvl
3 1.2 3.5   a
1 2.2 4.5   a
2 3.2 2.5   a
5 2.2 7.5   b
6 3.2 6.5   b
4 4.2 5.5   b
8 1.2 1.5   c
7 2.2 2.5   c
9 5.2 3.5   c
于 2013-09-17T00:08:04.257 回答
3

使用dplyr,您可以添加.by_group = TRUEarrange()以对每个组中的列进行排序。尝试:

library(dplyr)
d %>% 
        group_by(lvl) %>%
        arrange(v1, .by_group = TRUE)
# output
# A tibble: 9 x 3
# Groups:   lvl [3]
     v1    v2    lvl
  <dbl> <dbl> <fctr>
1   1.2   3.5      a
2   2.2   4.5      a
3   3.2   2.5      a
4   2.2   7.5      b
5   3.2   6.5      b
6   4.2   5.5      b
7   1.2   1.5      c
8   2.2   2.5      c
9   5.2   3.5      c
于 2018-09-28T16:12:15.727 回答
1

我相信这也是一个合法的解决方案,使用dplyr

require(data.table)
require(dplyr)
require(dtplyr)

DT <- as.data.table(d)
DT %>% group_by(lvl) %>% arrange(v1)
于 2017-11-20T05:07:34.020 回答