我有一个列表和一个数据框
l <- list("a" = c(1, 2), "b" =c(1, 3))
id value
a 3
b 2
我想通过将ID与列表名称匹配来同时考虑列表和数据帧,从而通过ID获得数据帧中值的排名。例如,如果我们认为a,3在1、2、3中最大,则需要将其排名为1。与b,2相似,在1、2、3中是第二大,我们将其排名为2。所需的输出应为
id value
a 1
b 2
答案 0 :(得分:2)
生成样本数据:
l <- list("a" = c(1, 2), "b" =c(1, 3))
df <- data.frame(id = c("a", "b"), value = c(3, 2))
生成您的反向排名:
df$value <- unlist(lapply(df$id, function(x){ # Apply a function
# over the unique
# ids in df
r <- df[df$id == x,] # Get the row from
# the df
vec <- c(unlist(l[names(l) == x]), r$value)# Construct the
# complete vector
# including the
# value to test
rank(-vec)[length(vec)] # rank the negative
# of the vector and
# return the last
# value
}))
> df
id value
1 a 1
2 b 2
答案 1 :(得分:1)
我不确定我是否完全遵循您的问题。我将其解释为您只有一个值,您想知道它在较长向量中的位置。
#Create your data
l <- list("a" = c(1, 2), "b" =c(1, 3))
df <- data.frame(id = c("a", "b"), value = c(3, 2))
df$rankValue <- sapply(names(l), function(n) {
combinedVector = c(l[[n]], df[which(df$id == n),"value"]) # we know the value from df is placed last
ordering <- order(combinedVector, decreasing = TRUE) # find which order are the numbers in
which(ordering == length(ordering)) # where (or which rank) is the last number (the input number)
})
> df
id value rankValue
1 a 3 1
2 b 2 2