R 使用列表和数据框对值进行排序
我有一个列表和一个数据框R 使用列表和数据框对值进行排序,r,lapply,R,Lapply,我有一个列表和一个数据框 l <- list("a" = c(1, 2), "b" =c(1, 3)) id value a 3 b 2 生成您的示例数据: l <- list("a" = c(1, 2), "b" =c(1, 3)) df <- data.frame(id = c("a", "b"), value = c(3, 2)) l我不确定我是否完全明白你的问题。我解释为,你有一个值,你想知道它在一个较长的向量中的位置 #Create
l <- list("a" = c(1, 2), "b" =c(1, 3))
id value
a 3
b 2
生成您的示例数据:
l <- list("a" = c(1, 2), "b" =c(1, 3))
df <- data.frame(id = c("a", "b"), value = c(3, 2))
l我不确定我是否完全明白你的问题。我解释为,你有一个值,你想知道它在一个较长的向量中的位置
#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
#创建您的数据
l在此上下文中,列表的目的是什么?仅使用data.frame
是否可以生成所需的输出?
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
#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