Skip to content
Prev 294383 / 398502 Next

Subset and order at the same time?

Hi Noah,

I think it is hard to say what is best without your real example.  Is
the goal elegance or speed?  I have not tried it, but if you are
ordering say 9/10 groups, I would think you are better off calling
order once, even though you will not use it for one group.

I also think if you are ordering multiple groups, you should take
advantage of that and do it all at once rather than in a series of one
liners.

## A
sleep$index <- order(sleep$extra)
sleep[sleep$group == 1, ] <- with(subset(sleep, group == 1), sleep[index, ])

## A "one line"
sleep$index <- order(sleep$extra); sleep[sleep$group == 1, ] <-
with(subset(sleep, group == 1), sleep[index, ])

## B
sleep[sleep$group == 1, ] <- with(subset(sleep, group == 1),
sleep[order(extra), ])

I agree with Neal though, the one line solutions are probably
something you can do but probably should not do.  At an extreme:

a <- b <- 10; dat <- local(data.frame(first = b, second = a <- 0 -> b,
third = a <- rnorm(10, mean = a), fourth = a / 2, fifth = a <-
rnorm(10, mean = a <- b), sixth = a * rnorm(10, b) -> a, seventh = b
<<- a^2, eigth = {rm(b); 1:10}, ninth = a * b, tenth = b <<- a -> b,
eleventh = {rm(a); b <- 10:1}, twelth = a, thirteenth = local(a <<- b
-> a)))

Cheers,

Josh
On Sat, May 12, 2012 at 1:04 PM, Neal Fultz <nfultz at gmail.com> wrote: