【问题标题】:Count instances in list-column row by row逐行计算列表列中的实例
【发布时间】:2018-09-20 02:44:46
【问题描述】:

我正在使用包含整数列表列的数据框。 list-column 中的每个元素对应于数据框中的一行,现在我想计算一下有多少个链接。

dput 包含一列 link_count,指示此数据样本的正确计数:

move link_count links
   1          1    NA
   2          0     1
   3          1    NA
   4          1     3
   5          4     4
   6          1     5
   7          0  5, 6
   8          2     5
   9          0     8
  10          0  5, 8

#dput results saved as `x`
x <- structure(list(move = 1:10, link_count = c(1, 0, 1, 1, 4, 1, 0, 2, 0, 0), links = list(NA_integer_, 1L, NA_integer_, 3L, 4L, 5L, 5:6, 5L, 8L, c(5L, 8L))), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("move", "link count", "links"))

我找到了一个使用 left_join 的解决方案,但我认为可能有一个更优雅的解决方案可以使用 dplyr::mutatepurrr::map 工作流逐行完成。我希望可以在一系列管道中完成一些事情。

#This works, but is there a different way?
left_join(x,
      x %>% unnest(links) %>% count(links),
      by = c("move" = "links"))

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    base R 选项将是。这里,缺少的元素是NA,而不是0s

    as.numeric(table(unlist(x$links))[as.character(x$move)])
    

    【讨论】:

      【解决方案2】:

      base R 的另一个选项完全基于@akrun 答案:

      x$n <- as.numeric(table(factor(unlist(x$links), levels = x$move)))
      

      【讨论】:

        【解决方案3】:

        只是为了改变节奏,我将提供一个 dplyr 答案。您可以使用right_join 保持管道滚动:

        x %>%
          unnest(links) %>%
          group_by(links) %>%
          summarise(link_count=n()) %>%
          right_join(x, by=c("links"="move"))
        
        ## A tibble: 10 x 4
        #   links link_count `link count`   links.y
        #   <int>      <int>        <dbl>    <list>
        # 1     1          1            1 <int [1]>
        # 2     2         NA            0 <int [1]>
        # 3     3          1            1 <int [1]>
        # 4     4          1            1 <int [1]>
        # 5     5          4            4 <int [1]>
        # 6     6          1            1 <int [1]>
        # 7     7         NA            0 <int [2]>
        # 8     8          2            2 <int [1]>
        # 9     9         NA            0 <int [1]>
        #10    10         NA            0 <int [2]>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-11-30
          • 2013-04-08
          • 1970-01-01
          • 2018-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多