在R中提取预测变量形式的constparty对象(CHAID输出)

时间:2013-10-16 08:00:25

标签: r tree party

我有大量分类变量的大型数据集(问卷调查结果)。我已经使用卡方检验测试了变量之间的依赖性。变量之间存在难以理解的依赖关系数量。我使用CHAID包中的chaid()函数来检测交互并将每个变量的这些依赖关系的底层结构分开(我希望是什么)。通常情况下,卡方检验会显示变量的大量依赖关系(比如说10-20),而chaid函数会将其减少到更容易理解的范围(例如3-5)。我想要做的是提取那些在chaid()结果中显示相关的变量的名称。

chaid()输出采用constparty对象的形式。我的问题是如何提取与这种对象中的节点相关联的变量名称。

这是一个自包含的代码示例:

library(evtree) # for the ContraceptiveChoice dataset
library(CHAID)
library(vcd)
library(MASS)

data("ContraceptiveChoice")
longform = formula(contraceptive_method_used ~ wifes_education + 
                 husbands_education +  wifes_religion + wife_now_working + 
                 husbands_occupation + standard_of_living_index + media_exposure)
z = chaid(longform, data = ContraceptiveChoice)
# plot(z)
z
# This is the part I want to do programatically
shortform = formula(contraceptive_method_used ~ wifes_education + husbands_occupation)
# The thing I want is a programatic way to extract 'shortform'  from 'z' 

# Examples of use of 'shortfom'   
loglm(shortform, data = ContraceptiveChoice)

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案:

nn <- nodeapply(z)
n.names= names(unlist(nn[[1]]))
ext <- unlist(sapply(n.names, function(x) grep("split.varid.", x, value=T)))
ext <- gsub("kids.split.varid.", "", ext)
ext <- gsub("split.varid.", "", ext)
dep.var <- as.character(terms(z)[1][[2]]) # get the dependent variable
plus = paste(ext, collapse=" + ")     
mul = paste(ext, collapse=" * ")
shortform <- as.formula(paste (dep.var, plus, sep = " ~ "))
satform <- as.formula(paste (dep.var, mul, sep = " ~ "))
mosaic(shortform, data = ContraceptiveChoice)
#stp <- step(glm(satform, data=ContraceptiveChoice, family=binomial), direction="both")