首页 > 解决方案 > 使用`ddply`从两列中选择基于匹配对的列的最常见值

问题描述

我正在尝试使用ddply(一个plyr函数)从以下形式的社交媒体数据中对任何唯一用户对之间最频繁的交互类型进行排序和识别

from <- c('A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'D', 'D', 'D', 'D')
to <- c('B', 'B', 'D', 'A', 'C', 'C', 'D', 'A', 'D', 'B', 'A', 'B', 'B', 'A', 'C')
interaction_type <- c('like', 'comment', 'share', 'like', 'like', 'like', 'comment', 'like', 'like', 'share', 'like', 'comment', 'like', 'share', 'like')

dat <- data.frame(from, to, interaction_type)

如果聚合正确,应该找到任何唯一对之间最常见的交互类型(无论方向性如何(即 A-->B,A<--B)),就像这样

from    to  type
A       B   like
A       C   like
A       D   share
B       C   like
B       D   comment
C       D   like

虽然通过使用很容易获得任意两个用户之间的交互总数

count <- ddply(sub_test, .(from, to), nrow)

我发现很难应用类似的方法来找到使用这种聚合方法的任何给定对之间最常见的交互类型。实现我想要的输出的最有效方法是什么?另外,如何处理可能的“捆绑”案件?(我可能只使用“tided”作为所有已绑定案例的单元格值)。

标签: rplyraggregationpairwise

解决方案


from无论列的顺序如何,我们都需要找到每组最常见的值(模式)to

这个答案中获取Mode功能

Mode <- function(x) {
   ux <- unique(x)
   ux[which.max(tabulate(match(x, ux)))]
}

我们可以dplyr用来获取组的第一个出现的最大值。

library(dplyr)

dat %>%
  mutate(key = paste0(pmin(from, to), pmax(from, to), sep = "")) %>%
  group_by(key) %>%
  mutate(interaction_type = Mode(interaction_type)) %>%
  slice(1) %>%
  ungroup() %>%
  select(-key)

#  from  to    interaction_type
#  <chr> <chr> <chr>           
#1 A     B     like            
#2 C     A     like            
#3 A     D     share           
#4 B     C     like            
#5 B     D     comment         
#6 C     D     like     

通过添加数据将列保留为字符stringsAsFactors = FALSE


推荐阅读