From the following list of values.
list_for_rank <- c(3,8,11)
Get the rank position of every row of column "value" as new column
df <- data.frame(id = c("xx1", "xx2","xx3","xx4","xx5"), value = c(10,6,3,7,9))
Expected result should be something like this new column "rank_position"
df <- data.frame(id = c("xx1", "xx2","xx3","xx4","xx5"),
value = c(10,6,3,7,9),
rank_position=c(3,2,1,3,3))
Explanation: Value = 10 ranks 3th in list "list_for_rank" whereas value=6 ranks 2 on the list called "list_for_rank " and so on.
CodePudding user response:
df <- data.frame(id = c("xx1", "xx2","xx3","xx4","xx5"), value = c(10,6,3,7,9))
list_for_rank <- c(3,8,11)
using dplyr
library(dplyr)
df %>%
group_by(value) %>%
mutate(list_for_rank = rank(c(value, list_for_rank), ties.method = "first")[1])
# # A tibble: 5 x 3
# # Groups: value [5]
# id value list_for_rank
# <fct> <dbl> <int>
# 1 xx1 10 3
# 2 xx2 6 2
# 3 xx3 3 1
# 4 xx4 7 2
# 5 xx5 9 3
using data.table
library(data.table)
setDT(df)
df[, list_for_rank := rank(c(value, list_for_rank), ties.method = "first")[1], by = value]
df
# id value list_for_rank
# 1: xx1 10 3
# 2: xx2 6 2
# 3: xx3 3 1
# 4: xx4 7 2
# 5: xx5 9 3
