R语言Apriori算法:如何排除no值仅保留yes关联规则?
解决Apriori规则仅保留含"yes"项的问题
问题原因
你当前代码中appearance=list(...)的default="lhs"参数是关键问题:它指定所有未在lhs/rhs列表中明确列出的项(即所有带no的项),默认可以被包含在规则的LHS部分,这就是为什么结果中会出现Made.in.effect=no这类项。
两种可行解决方案
方案1:修正appearance参数配置
通过设置default="none",禁止所有未明确指定的项出现在规则的任何部分,同时明确列出所有允许的yes项:
# 定义所有允许的"yes"项集合 allowed_yes_items <- c( "Firm.s.global.reorganization=yes", "Delivery.time=yes", "Automation.of.production.process=yes", "Poor.quality.of.offshored.production=yes", "Made.in.effect=yes", "Proximity.to.customers=yes", "Implementation.of.strategies.based.on.product.process.innovation=yes", "Untapped.production.capacity=yes", "Know.how.in.the.home.country=yes", "Change.in.total.costs.of.sourcing=yes", "Logistics.costs=yes", "Need.for.greater.organizational.flexibility=yes", "Economic.crisis=yes", "Improve.customer.service=yes", "Labour.costs..gap.reduction=yes", "Government.support.to.relocation=yes", "Proximity.to.suppliers=yes", "Loyalty.to.the.home.country=yes" ) # 运行Apriori,严格限制仅允许指定的yes项 rules7 <- apriori( data4, parameter = list(support = 0.05, confidence = 0.5, maxlen=5), appearance = list( rhs = c("Firm.s.global.reorganization=yes"), lhs = setdiff(allowed_yes_items, "Firm.s.global.reorganization=yes"), # 排除RHS的项作为LHS default = "none" # 禁止所有未列出的项 ) )
方案2:预处理数据集,仅保留"yes"项
先将原始数据转换为仅包含yes项的事务对象,这样生成的规则自然不会出现no相关内容:
# 逐行提取值为"yes"的变量名,转换为事务格式 transactions <- apply(data4, 1, function(row) { names(row)[row == "yes"] }) transactions <- as(transactions, "transactions") # 在纯yes事务上运行Apriori rules7 <- apriori( transactions, parameter = list(support = 0.05, confidence = 0.5, maxlen=5), appearance = list( rhs = c("Firm.s.global.reorganization"), default = "lhs" ) )
验证效果
运行上述任一方案后,生成的规则LHS和RHS将仅包含带yes的项,不会再出现no相关的条目。
内容的提问来源于stack exchange,提问作者Jelle M
相关产品推荐
相关产品推荐

