user1998031
user1998031

Reputation: 127

Sorting within a data frame keeping one column fixed

I have a data frame like this :

  a v
1 g 9
2 g 2
3 z 2
4 z 3
5 a 5
6 a 4

I want to keep the column 'a' intact [unsorted as it is] and sort column 'v' within column 'a'. The resulting output should be like this:

  a v
1 g 2
2 g 9
3 z 2
4 z 3
5 a 4
6 a 5

I tried using the order command, but then I have to sort by both the columns. Can some one please help me with it ?

thanks!

Upvotes: 1

Views: 1202

Answers (3)

Matthew Lundberg
Matthew Lundberg

Reputation: 42689

Expanding on @GregSnow to the case where there are more than the two columns (as I can see actually using it that way).

Sort by v according to groups in a, keeping x:

d <- read.table(header=TRUE, text="  a v x
1 g 9 10
2 g 2 20
3 z 2 30
4 z 3 40
5 a 5 60
6 a 4 70")

ord <- ave(seq_along(d$a)-1, d$a, FUN=min) + ave(d$v, d$a, FUN=order)

d[ord,]
##   a v  x
## 2 g 2 20
## 1 g 9 10
## 3 z 2 30
## 4 z 3 40
## 6 a 4 70
## 5 a 5 60

Upvotes: 2

Justin
Justin

Reputation: 43265

The data.table package makes this easy:

library(data.table)

dat <- structure(list(a = c("g", "g", "z", "z", "a", "a"), v = c(9L, 
2L, 2L, 3L, 5L, 4L)), .Names = c("a", "v"), row.names = c(NA, 
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x1b2cba8>)

dat[, list(v=sort(v)), by=a]

#    a  v
# 1: g  2
# 2: g  9
# 3: z  2
# 4: z  3
# 5: a  4
# 6: a  5

Upvotes: 7

Greg Snow
Greg Snow

Reputation: 49660

Here is an approach that uses the ave function:

> dat$v <- ave(dat$v, dat$a, FUN=sort)
> dat
  a v
1 g 2
2 g 9
3 z 2
4 z 3
5 a 4
6 a 5

Upvotes: 10

Related Questions