gpt4 book ai didi

R:计算列可互换的数据框中的不同组合

转载 作者:行者123 更新时间:2023-12-03 13:33:20 24 4
gpt4 key购买 nike

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

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 方法最受欢迎!

最佳答案

通过使用 applysort订购您的数据框,然后我们只使用 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

关于R:计算列可互换的数据框中的不同组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com