I have a dataframe and then have ranked the values across each row. I’m looking to update this so that if the value in the original data frame is <=0 the rank value become 0, otherwise keep the rank number.
So with the example data below rank rows 1 & 2 would become:
0 1 0
0 0 1
example data:
df <- data.frame(score_1 = floor(runif(10, min=-10, max=10)),
score_2 = floor(runif(10, min=-10, max=10)),
score_3 = floor(runif(10, min=-10, max=10)))
score_1 score_2 score_3
1 -3 4 -7
2 0 -10 5
3 -2 -8 -8
4 -6 -6 3
5 -2 -6 -7
6 -1 -4 -4
7 -10 -7 2
8 0 7 3
9 -10 6 -1
10 9 -5 -3
rank <- df %>%
rowwise() %>%
do(data.frame(t(rank(-unlist(.)))))
rank
score_1 score_2 score_3
1 2 1 3
2 2 3 1
3 1 2.5 2.5
4 2.5 2.5 1
5 1 2 3
6 1 2.5 2.5
7 3 2 1
8 3 1 2
9 3 1 2
10 1 3 2
>Solution :
Since the two dataframes are of same dimensions you can do a direct replacement.
rank[df <= 0] <- 0
rank
# score_1 score_2 score_3
# <dbl> <dbl> <dbl>
# 1 0 1 0
# 2 0 0 1
# 3 0 0 0
# 4 0 0 1
# 5 0 0 0
# 6 0 0 0
# 7 0 0 1
# 8 0 1 2
# 9 0 1 0
#10 1 0 0