我想在 R 中修改我的数据集,以便我可以进行购物篮分析

问题描述 投票:0回答:1

我需要在 R 中修改我的数据集,它看起来像一个经典表格,行中有观察值,列中有变量。具体来说,第一列报告一组由 ID 代码 (InvoiceNo) 标识的交易,第二列表示产品描述。 我在数据集的图像下方重现它出现的样子。 enter image description here

具体来说,我的目的是获得一个表格,该表格适合用于市场篮子分析,其中按行有不同的交易(发票号),按列有不同的属性(描述)。换句话说,我想获取二进制数据,指示该特定交易中是否存在该特定产品(在描述列中报告)。 我在数据集的图像下方重现了我希望它看起来的样子: enter image description here

r reshape binary-data reshape2 market-basket-analysis
1个回答
0
投票

您可以使用

pivot_wider
来自
tidyr
.

创建与您的结构相同的数据集:

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

df <- tibble(id = c(1,2,3,4,5,6), description = c('lalalala', 'blob', 'blob', 'foo', 'foo', 'lalalala'))

应用功能:

df %>%
  mutate(for_pivot = 1) %>% # creating a new column for your binary output
  pivot_wider(id_cols = 'id', names_from = 'description', values_from = 'for_pivot') %>% # pivoting
  mutate_all(coalesce, 0) # transforming all NA as 0
© www.soinside.com 2019 - 2024. All rights reserved.