R. hacker
R. hacker

Reputation: 11

How to rank in r for a given condition?

I have a vector

x<-c(1,5,0.4,1.3,0.2,0.6)

I want to rank x in decreasing order only for the values that are greater than 1. I don't to change the x vector by removing values that are less than 1.

My desired output is like

rank=c(3,1,Null,2,Null,Null)

Can anyone help me?

Upvotes: 0

Views: 917

Answers (3)

989
989

Reputation: 12937

You could do this:

rnk <- rep(NA, length(x))
w <- which(x>=1)
rnk[w] <- rank(-x[w])

#[1]  3  1 NA  2 NA NA

Upvotes: 1

mpschramm
mpschramm

Reputation: 550

Using dplyr:

df <- data.frame(x=c(1,5,0.4,1.3,0.2,0.6))

library(dplyr)
df <- df %>%
   mutate(filtered = ifelse(x<1, NA, x)) %>%
   mutate(rank = rank(-filtered, na.last = "keep"))
df

    x filtered rank
1 1.0      1.0    3
2 5.0      5.0    1
3 0.4       NA   NA
4 1.3      1.3    2
5 0.2       NA   NA
6 0.6       NA   NA

Upvotes: 0

etienne
etienne

Reputation: 3678

You can do it like this:

x <- c(1,5,0.4,1.3,0.2,0.6)
temp <- x
temp[temp < 1] <- NA
rank(-temp, na.last = "keep") # -temp so that the decreasing order is used

# [1]  3  1 NA  2 NA NA

Upvotes: 1

Related Questions