我如何计算,在一个会话中总共有多少个项目?

RKF*_*RKF 0 r dplyr tidyr tidyverse data-wrangling

我真的尽我最大的努力通过 stackoverflow 搜索解决方案,但不幸的是我找不到合适的问题。因此,我必须自己提出一个问题。

我正在处理一个包含 sessionID 和主题的数据集。想象它看起来像这样:

sessionID <- c(1, 2, 2, 3, 4, 4, 5, 6, 6, 6)
topic <- c("rock", "house", "country", "rock", "r'n'b", "pop", "classic", "house", "rock", "country")
transactions <- cbind(sessionID, topic)
transactions
Run Code Online (Sandbox Code Playgroud)

现在,我想知道某个主题的多少项目一起出现在一个会话中。最后,我想获得一个矩阵,表示特定主题与其他主题进行会话的频率。最终结果应如下所示:

topics <- sort(unique(topic))
topicPairs <- matrix(NA, nrow = length(topics), ncol = length(topics))
colnames(topicPairs) <- topics
rownames(topicPairs) <- topics
topicPairs["house", "country"] <- 2
topicPairs["country", "house"] <- 2
topicPairs["r'n'b", "pop"] <- 1
topicPairs["pop", "r'n'b"] <- 1
topicPairs["rock", "house"] <- 1
topicPairs["house", "rock"] <- 1
topicPairs["rock", "country"] <- 1
topicPairs["country", "rock"] <- 1
topicPairs["house", "house"] <- 2
topicPairs
Run Code Online (Sandbox Code Playgroud)

例如,在“house”行中,“country”列应等于 2,因为“house”在第 2 和第 6 次会话中与“country”一起出现。

在我期望的主要对角线上,一个主题在会话中总共出现的频率。在这里,行“house”列“house”等于 2,因为它已经在两个会话中......但我不确定这一点。

如果您的解决方案不包含循环,那就太棒了,因为我的数据集非常大。因此,我更喜欢 tidyverse 中的函数(dplyr、tidyr 等)。也许是 group_by 和 tidyr 包中的 spread 函数的组合。

我真的在寻找你的答案。非常感谢您提前!

亲切的问候!

Gre*_*reg 5

如果您不介意通过包执行jointransactions对自身)dplyr,以下应该有效:

library(dplyr)
library(tibble)
library(tidyr)

# ...
# Your existing code that created `transactions`.
# ...

# Convert transactions to a dataframe for transformation.
transactions <- as.data.frame(transactions)

result <- transactions %>%
  # Create pairings of topics by session.
  inner_join(transactions, by = "sessionID", suffix = c(".r", ".c")) %>%
  # "Pivot" the pairings, such that each topic within `topics.c` gets its own
  # column; and then aggregate the pairings by count.
  pivot_wider(id_cols = c(sessionID, topic.r),
              names_from = topic.c,
              values_from = sessionID,
              values_fn = length,
              names_sort = TRUE) %>%
  # Sort appropriately, to align the main diagonal.
  arrange(topic.r) %>%
  # Convert to matrix form, with topics as row names.
  column_to_rownames(var = "topic.r") %>% as.matrix()

# View result.
result
Run Code Online (Sandbox Code Playgroud)

这是result我最后的打印输出:

        classic country house pop r'n'b rock
classic       1      NA    NA  NA    NA   NA
country      NA       2     2  NA    NA    1
house        NA       2     2  NA    NA    1
pop          NA      NA    NA   1     1   NA
r'n'b        NA      NA    NA   1     1   NA
rock         NA       1     1  NA    NA    3
Run Code Online (Sandbox Code Playgroud)

更新

建议更优雅(更不用提聪明),并且只需要以下

# ...
# Your existing code that created `transactions`.
# ...

# Compute the results.
result <- crossprod(table(as.data.frame(transactions)))
# Substitute NAs for 0s, if you so desire.
result <- ifelse(result == 0, NA, result)
Run Code Online (Sandbox Code Playgroud)

达到相同的结果。我不能保证任一解决方案在大型数据集上的相对性能。