【发布时间】: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