R how to selectively sort a data frame?

I have the following sample 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 by = column index. Now I would like to sort it by column ptr, but leaving the position of the rows, where ptr= NAuntouched. Therefore, I expect:

  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

Normal df = df[order(ptr),]does not work. Any ideas? Thank you very much in advance.

+3
source share
2 answers

try the following:

> 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
+9
source
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
+4
source

All Articles