识别 R 中排名不同列中的关系

Identifying ties in a different column of a rank in R

我正在使用 R。

我有一组数据是这样的。

principal    percentage     ranked
love            25            1
love            25            2
love            22            3
love            21            4
love            20            5
table           30            1
table           20            2
table           19            3
table           18            4
table           5             5

所以,我需要知道在百分比列中排在第 1 位和第 2 位的词是否并列。

例如,我想要这样的输出。

principal    tie
love         TRUE
table        FALSE

谢谢。

您可以使用以下-

library(dplyr)

df %>%
  group_by(principal) %>%
  summarise(tie = percentage[match(1, ranked)] == percentage[match(2, ranked)])

#   principal tie  
#  <chr>     <lgl>
#1 love      TRUE 
#2 table     FALSE

类似的替代方案是 -

#2.
df %>% 
   group_by(principal) %>% 
   summarise(tie = percentage[ranked == 1] == percentage[ranked == 2])

#3.
df %>%
  arrange(principal, ranked) %>%
  group_by(principal) %>%
  summarise(tie = percentage[1] == percentage[2])

更新:感谢akrun_master的宝贵意见!已删除 ifelse

library(dplyr)

# helper function to coalesce by column
coalesce_by_column <- function(df) {
  return(coalesce(df[1], df[2]))
}

            
df %>% 
  group_by(principal) %>% 
  mutate(ties = percentage[1] == percentage[2], TRUE, FALSE) %>% 
  summarise(Comments = coalesce_by_column(ties))

输出:

  principal Comments
  <chr>     <lgl>   
1 love      TRUE    
2 table     FALSE