问题描述
我正在尝试使用 ddply
(一个 plyr
函数)对最常见的交互类型进行排序和识别在以下形式的社交媒体数据中的任何唯一用户对之间
I'm trying to use ddply
(a plyr
function) to sort and identify the most frequent interaction type between any unique pairs of user from a social media data of the following form
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
which, if aggregate correctly, should find the most common type of interaction between any unique pairs (regardless of directionality (i.e., A-->B, A<--B)) like this
from to type
A B like
A C like
A D share
B C like
B D comment
C D like
这样的CD,虽然很容易通过使用
While it's easy to get the total count of interaction between any two users by using
count <- ddply(sub_test, .(from, to), nrow)
我发现使用这种聚合方法很难应用类似的方法来找到任何给定对之间最常见的交互类型。实现所需输出的最有效方法是什么?另外,如何处理可能的绑架案件? (我可能只使用 tided作为所有绑定案例的单元格值)。
I found it hard to apply similar method to find the most common type of interaction between any given pairs with this aggregation method. What will be the most efficient way to achieve my desired output? Also, how to handle possible "tied" cases? (I might just use "tided" as the cell values for all tied cases).
推荐答案
类似于Ronak的方法
Similar to Ronak's approach
library(dplyr)
dat <- data.frame(from, to, interaction_type, stringsAsFactors = F)
dat %>%
mutate(
pair = purrr::pmap_chr(
.l = list(from = from, to = to),
.f = function(from, to) paste(sort(c(from, to)), collapse = "")
)
) %>%
group_by(pair) %>%
filter(n() == max(n()) & row_number() == 1) %>%
ungroup() %>%
select(-pair)
# A tibble: 6 x 3
from to interaction_type
<chr> <chr> <chr>
1 A B like
2 A D share
3 B C like
4 B D comment
5 C A like
6 C D like
这篇关于使用ddply从两列中的匹配对中选择一列的最常用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!