【发布时间】:2016-06-17 15:55:16
【问题描述】:
我有一个项目列表的数据框,其中数据框中的每一行都包含 LHS 和 RHS 关联规则以及相应的支持度、置信度和提升度。 这是数据:
structure(list(rules = structure(c(13L, 4L, 28L, 1L, 24L, 15L
), .Label = c("{butter,jam} => {whole milk}", "{butter,rice} => {whole milk}",
"{canned fish,hygiene articles} => {whole milk}", "{curd,cereals} => {whole milk}",
"{domestic eggs,rice} => {whole milk}", "{grapes,onions} => {other vegetables}",
"{hamburger meat,bottled beer} => {whole milk}", "{hamburger meat,curd} => {whole milk}",
"{hard cheese,oil} => {other vegetables}", "{herbs,fruit/vegetable juice} => {other vegetables}",
"{herbs,rolls/buns} => {whole milk}", "{herbs,shopping bags} => {other vegetables}",
"{liquor,red/blush wine} => {bottled beer}", "{meat,margarine} => {other vegetables}",
"{napkins,house keeping products} => {whole milk}", "{oil,mustard} => {whole milk}",
"{onions,butter milk} => {other vegetables}", "{onions,waffles} => {other vegetables}",
"{pastry,sweet spreads} => {whole milk}", "{pickled vegetables,chocolate} => {whole milk}",
"{pork,butter milk} => {other vegetables}", "{rice,bottled water} => {whole milk}",
"{rice,sugar} => {whole milk}", "{soups,bottled beer} => {whole milk}",
"{tropical fruit,herbs} => {whole milk}", "{turkey,curd} => {other vegetables}",
"{whipped/sour cream,house keeping products} => {whole milk}",
"{yogurt,cereals} => {whole milk}", "{yogurt,rice} => {other vegetables}"
), class = "factor"), support = c(0.00193187595322827, 0.00101677681748856,
0.00172852058973055, 0.00101677681748856, 0.00111845449923742,
0.00132180986273513), confidence = c(0.904761904761905, 0.909090909090909,
0.80952380952381, 0.833333333333333, 0.916666666666667, 0.8125
), lift = c(11.2352693602694, 3.55786275006331, 3.16819206791352,
3.26137418755803, 3.58751160631383, 3.17983983286908)), .Names = c("rules",
"support", "confidence", "lift"), row.names = c(NA, 6L), class = "data.frame")
我需要将这些规则结构化为宽格式,其中规则的每个 LHS 部分中的每个项目都有一个值为 1 的指定列(表示该规则在其 LHD 部分中有该项目) , 规则的 RHS 也是如此,例如采用两条第一条规则:
{liquor,red/blush wine} => {bottled beer} 0.0019 0.90 11.2
{curd,cereals} => {whole milk} 0.0010 0.91 3.6
结果应该是一个如下所示的数据框:
'rules_id' 'lhs_liquor' 'lhs_red/blush wine' 'lhs_curd' 'lhs_cereals' 'rhs_bottled beer' 'rhd_whole milk' 'support' 'confidence' 'lift'
1 1 1 0 0 1 0 0.0019 0.90 11.2
2 0 0 1 1 0 1 0.0010 0.91 3.6
由于我是 R 新手和堆栈溢出,如果问题没有明确定义,请告诉我 任何帮助表示赞赏
【问题讨论】:
-
你的最后一段,因为它不是问题本身的一部分,所以通常会出现在 cmets 中。
-
长格式可能更有用:
df %>% separate(col = rules, into = c('lhs', 'rhs'), sep = ' => ') %>% separate_rows(col = lhs, into = lhs, sep = ',') %>% gather(key = side, value = product, lhs, rhs) %>% mutate(product = gsub('[{}]', '', product))