Mefhisto1
Mefhisto1

Reputation: 2228

Order a data frame only from a certain row index to a certain row index

Let's say we have a DF like this:

col1 col2 
A   1
A   5
A   3
A   16
B   5
B   4
B   3
C   7
C   2

I'm trying to order col2 but only for same values in col1. Better said, I want it to look like this:

 col1 col2 
    A   1
    A   3
    A   5
    A   16
    B   3
    B   4
    B   5
    C   2
    C   7

So order col2 only for A, B and C values, not order the entire col2 column

x <- function() {
    values<- unique(DF[, 1])

      for (i in values) {
        currentData <- which(DF$col1== i)

## what to do here ?

        data[order(data[, 2]), ]
      }

}

so in CurrentData I have indexes for col2 values for only As, Bs etc. But how do I order only those items in my entire DF data frame ? Is it somehow possible to tell the order function to do order only on certain row indexes of data frame ?

Upvotes: 0

Views: 77

Answers (2)

James King
James King

Reputation: 6355

It seems that

my_df[with(my_df, order(col1, col2)), ]

will do what you want - this just sorts the dataframe by col1 and col2. If you don't want to order by col1 a method is provided in the other answer.

Upvotes: 4

Matthew Lundberg
Matthew Lundberg

Reputation: 42629

ave will group the data by the first element, and apply the named function to the second element for each group. Here is an application of ave sorting within groups:

DF$col2 <- ave(DF$col2, DF$col1, FUN=sort)
DF
##   col1 col2
## 1    A    1
## 2    A    3
## 3    A    5
## 4    A   16
## 5    B    3
## 6    B    4
## 7    B    5
## 8    C    2
## 9    C    7

This will work even if the values in col1 are not consecutive, leaving them in their original positions.

If that is not an important consideration, there are better ways to do this, such as the answer by @user314046.

Upvotes: 5

Related Questions