代码之家  ›  专栏  ›  技术社区  ›  Chris T.

使用“ddply”从两列中选择基于匹配对的列的最常用值`

  •  0
  • Chris T.  · 技术社区  · 6 年前

    我试着用 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)
    

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

    0 回复  |  直到 6 年前
        1
  •  2
  •   Sonny    6 年前

    类似于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
    
        2
  •  2
  •   Ronak Shah    6 年前

    无论列的顺序如何,我们都需要找到每组中最常见的值(模式) 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 在你的数据里。