简体   繁体   中英

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.

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM