对于给定的条件,如何在r中排名?

对于给定的条件,如何在r中排名?,r,rank,R,Rank,我有一个向量 x<-c(1,5,0.4,1.3,0.2,0.6) 有人能帮我吗?你可以这样做: 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 x您可以这样做: x <- c(1,5,0.4

我有一个向量

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

有人能帮我吗?

你可以这样做:

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

x您可以这样做:

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

x使用
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

df使用
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
df您可以这样做:

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

#[1]  3  1 NA  2 NA NA
rnk您可以这样做:

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

#[1]  3  1 NA  2 NA NA

rnk一行代码
replace(NA_real_ux>=1,秩(-x[x>=1])
One liner
replace(NA_real_ux>=1,秩(-x[x>=1])
非常感谢Etienne!!非常感谢艾蒂安!!非常感谢,非常感谢