broccoli
broccoli

Reputation: 4846

R how to selectively sort a data frame?

I have the following example data frame in R.

  item index  ptr
     A     1 0.40
     B     2   NA
     C     3 0.30
     D     4 0.35
     E     5 0.44
     F     6   NA

It is already sorted based on column = index. Now, I would like to sort it by the column ptr but by leaving the position of rows where ptr = NA intact. So the output I'm expecting is:

  item index  ptr
     C     3 0.30
     B     2   NA
     D     4 0.35
     A     1 0.40
     E     5 0.44
     F     6   NA

The regular df = df[order(ptr),] doesn't work. Any ideas? Thanks much in advance.

Upvotes: 3

Views: 338

Answers (2)

Brian Diggs
Brian Diggs

Reputation: 58835

ptr.na <- is.na(df$ptr)
order.idx <- seq(length=nrow(df))
ptr.idx <- which(!ptr.na)
order.idx[!ptr.na] <- ptr.idx[order(df[ptr.idx,"ptr"])]
df[order.idx,]

gives

> df[order.idx,]
  item index  ptr
3    C     3 0.30
2    B     2   NA
4    D     4 0.35
1    A     1 0.40
5    E     5 0.44
6    F     6   NA

Upvotes: 4

kohske
kohske

Reputation: 66852

try this:

> df
  item index  ptr
1    A     1 0.40
2    B     2   NA
3    C     3 0.30
4    D     4 0.35
5    E     5 0.44
6    F     6   NA
> df[!is.na(df$ptr), ] <- df[order(df$ptr, na.last = NA), ]
> df
  item index  ptr
1    C     3 0.30
2    B     2   NA
3    D     4 0.35
4    A     1 0.40
5    E     5 0.44
6    F     6   NA

Upvotes: 9

Related Questions