Dust009
Dust009

Reputation: 335

R: Sorting with a predetermined order

I have a dataframe that looks like this:

2,39  1
1,94  3
1,71  4
1,48  2

I'd like to sort to have a result like this:

2,39
1,71
1,48
1,94

Meaning that I first take the first element in the first column, then the third one, then the fourth one, ...

I first thought of using the apply function on the second column like this:

apply(... , sort)
apply(... , rev)

But doing so, I get:

2,39
1,48
1,94
1,71

I can have the desired result if I use a for loop but I wondered if there was a way to do this by using the apply function, which gives a cleaner code.

Upvotes: 1

Views: 221

Answers (1)

Tonio Liebrand
Tonio Liebrand

Reputation: 17719

simple indexing?

data <- data.frame(1:4)
data[, c(1,3,4,2)]

Upvotes: 1

Related Questions