如何在R中将数据转换为事务格式

问题描述

我有以下数据集,我想将其转换为事务格式。

sample_data<-data.frame(id=c(452,125,288,496,785,328,712,647),a=c(5,8,7,9,4,0),b=c(0,3,6,c=c(7,7),d=c(8,5,7))
sample_data

sample_data
id  a b c d
452 5 0 7 8
125 8 7 8 7
288 7 8 9 5
496 9 9 0 0
785 0 3 0 0
328 0 6 0 0
712 4 0 0 0
647 0 0 7 7

所需的输出如下:

id      item
452     a c d
125     a b c d
288     a b c d
496     a b
785     b
328     b
712     a
647     c d

如何在R中实现这一目标?

有没有更简单的方法

解决方法

这是使用tidyversepivot_longerfilter的{​​{1}}解决方案。

summarize
,

我们可以使用apply遍历行,获取数字列的值不为0的数据names,然后paste一起使用,然后{{1 }}和数据的第一列

cbind

-输出

cbind(sample_data[1],item = apply(sample_data[-1],1,function(x) paste(names(x)[x != 0],collapse = ' ')))