r - 使用`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”作为所有已绑定案例的单元格值)。
解决方案
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
。
推荐阅读
- android - Android Window 标志 FLAG_TRANSLUCENT_STATUS 现在已弃用,如何解决这个问题?
- aws-api-gateway - 如何通过 VPC 端点从 Route 53 访问私有 AWS API 网关?
- google-apps-script - 如果我们不时在 MS 中创建复制电子表格,我们如何同步宏?
- android - 如何在不使用 SafeArea 颤振的情况下检查设备是否有缺口?
- python - 为什么我的 django core.serializers 这么慢
- python - 如何按特定顺序放置熊猫数据框标头名称?
- java - Android 日期选择器显示不正确的格式
- java - Android Studio java不正确显示TextView
- objdump - 基于 objdump 的 dwarf 输出
- php - 如何在 Laravel 中将数组和子数组转换为集合?