1

I have a list and a data frame

l <- list("a" = c(1, 2), "b" =c(1, 3))
id   value
 a       3
 b       2

I want to get the rank of value in the data frame by id considering both list and data frame by matching id with list name. For example, if we consider a, 3 is the largest in 1, 2, 3, then we need to rank it as 1. Similar for b, 2 is the second largest in 1, 2, 3. we rank it as 2. The desired output should be

id   value
 a       1
 b       2
YellowRiver
  • 65
  • 1
  • 7
  • What is the purpose of the `list` in this context? Can the desired output not be produced with only the `data.frame`? – s_baldur Jan 18 '19 at 10:01

2 Answers2

2

Generate your sample data:

l <- list("a" = c(1, 2), "b" =c(1, 3))
df <- data.frame(id = c("a", "b"), value = c(3, 2))

Generate your reversed ranking:

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
trosendal
  • 1,225
  • 9
  • 14
1

I am not sure I completely follow your question. I interpret it as you have a single value which you want to know where it ranks in a longer vector.

#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
KnightofniDK
  • 139
  • 1
  • 1
  • 9