使用ddply从两列中的匹配对中选择一列的最常用值

编程入门 行业动态 更新时间:2024-10-27 18:30:04
本文介绍了使用ddply从两列中的匹配对中选择一列的最常用值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用 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 <-B))

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从两列中的匹配对中选择一列的最常用值

本文发布于:2023-07-26 07:07:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1214875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最常用   对中   ddply   两列中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!