Home > OS >  Rank order row values in R while keeping NA values
Rank order row values in R while keeping NA values

Time:12-17

I'm trying to convert values in a data frame to rank order values by row. So take this:

df = data.frame(A = c(10, 20, NA), B = c(NA, 10, 20), C = c(20, NA, 10))

When I do this:

t(apply(df, 1, rank))

I get this:

[1,] 1 3 2
[2,] 2 1 3
[3,] 3 2 1

But I want the NA values to continue showing as NA, like so:

[1,] 1 NA 2
[2,] 2 1 NA
[3,] NA 2 1

CodePudding user response:

Try using the argument na.last and set it to keep:

t(apply(df, 1, rank, na.last='keep'))

Output:

      A  B  C
[1,]  1 NA  2
[2,]  2  1 NA
[3,] NA  2  1

As mentioned in the documentation of rank:

na.last: for controlling the treatment of NAs. If TRUE, missing values in the data are put last; if FALSE, they are put first; if NA, they are removed; if "keep" they are kept with rank NA.

CodePudding user response:

Here a dplyr approach

Libraries

library(dplyr)

Data

df <- tibble(A = c(10, 20, NA), B = c(NA, 10, 20), C = c(20, NA, 10)) 

Code

df %>% 
  mutate(across(.fns = ~rank(x = .,na.last = "keep")))

Output

# A tibble: 3 x 3
      A     B     C
    <dbl> <dbl> <dbl>
1     1     NA    2
2     2     1     NA
3     NA    2     1
  • Related