我正在尝试使用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”作为所有绑定案例的单元格值)。
类似于Ronak的方法
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
我们需要找到每个组最常见的值(模式),而不管列from
,to
的顺序。
从Mode
回答this函数
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
将列保留为字符。