【问题标题】:R: counting distinct combinations found in a data frame where columns are interchangableR:计算在列可互换的数据框中找到的不同组合
【发布时间】:2018-11-09 22:45:09
【问题描述】:

我不确定这个问题到底叫什么。假设我正在计算 2 列的不同组合,但我希望两列的 order 不同。这就是我的意思:

df = data.frame(fruit1 = c("apple", "orange", "orange", "banana", "kiwi"),
                fruit2 = c("orange", "apple", "banana", "orange", "apple"),
                stringsAsFactors = FALSE)

# What I want: total number of fruit combinations, regardless of 
# which fruit comes first and which second.
# Eg 2 apple-orange, 2 banana-orange, 1 kiwi-apple

# What I know *doesn't* work:

table(df$fruit1, df$fruit2) 

# What *does* work:
library(dplyr)
df %>% group_by(fruit1, fruit2) %>% 
  transmute(fruitA = sort(c(fruit1, fruit2))[1],
            fruitB = sort(c(fruit1, fruit2))[2]) %>%
  group_by(fruitA, fruitB) %>%
  summarise(combinations = n())

如您所见,我有办法解决这个问题,但是这个一般问题有名称吗?这是一个组合问题,但计数,而不是生成组合。如果我有三四列类似的类型呢?上述方法泛化性较差。非常欢迎 Tidyverse 接近!

【问题讨论】:

    标签: r dplyr combinations


    【解决方案1】:

    通过使用apply 和sort 订购您的数据框,然后我们只使用group_by count

    data.frame(t(apply(df,1,sort)))%>%group_by_all(.)%>%count()
    # A tibble: 3 x 3
    # Groups:   X1, X2 [3]
          X1     X2     n
      <fctr> <fctr> <int>
    1  apple   kiwi     1
    2  apple orange     2
    3 banana orange     2
    

    【讨论】:

      【解决方案2】:

      这是一个使用pmap 和count 的选项

      library(tidyverse)
      library(rlang)
      pmap_df(df, ~ sort(c(...)) %>%
                       as.list %>%
                       as_tibble %>%
                       set_names(names(df))) %>% 
          count(!!! rlang::syms(names(.)))
      # A tibble: 3 x 3
      #  fruit1 fruit2     n
      #   <chr>  <chr>  <int>
      #1 apple  kiwi       1
      #2 apple  orange     2
      #3 banana orange     2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 2017-09-04
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多