Joy*_*Joy 7 combinations r dplyr
我不确定这个问题到底叫什么。假设我正在计算两列的不同组合,但我希望两列的顺序不同。这就是我的意思:
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())
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我有一种方法可以使这项工作正常进行,但是这个一般问题有名称吗?这是一个组合问题,但计数,而不是生成组合。如果我有三或四列类似的类型怎么办?上述方法泛化性较差。Tidyverse 方法最受欢迎!
通过使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |