作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
例如,假设我有一个受访者,询问他/她是否患有疾病。从那里我问她/他的父亲是否患有这种疾病。如果后一个问题是肯定的,那么我问父亲现在是否痊愈了。如果父亲没有患病,则该问题不适用。
我可以在 R 或其他地方创建这样的“决策树”吗?
以下是可用数据,其中 0 表示“否”,1 表示"is":
person_disease <- c(rep(1, 10), rep(0, 20))
father_disease <- c(rep(1, 7), rep(0,18), rep(1,5))
father_cured <- c( rep(0, 4), rep(1,3), rep(NA,18),rep(1,5) )
##
df <- data.frame(person_disease, father_disease, father_cured)
最佳答案
您可以使用 data.tree 包来实现这一点。有很多方法可以做你想做的事。例如:
person_disease <- c(rep(1, 10), rep(0, 20))
father_disease <- c(rep(1, 7), rep(0,18), rep(1,5))
father_cured <- c( rep(0, 4), rep(1,3), rep(NA,18),rep(1,5) )
df <- data.frame(person_disease, father_disease, father_cured)
library(data.tree)
#here, the tree is constructed "manually"
#however, depending on your data and your needs, you might want to generate the tree directly from the data
#many examples for this are available in the vignettes, see browseVignettes("data.tree")
disease <- Node$new("Disease", data = df)
father_disease_yes <- disease$AddChild("Father Disease Yes", label = "Father Disease", edge = "yes", condition = function(df) df[df$person_disease == 1,])
father_cured_yes <- father_disease_yes$AddChild("Father Cured Yes", label = "Father Cured", edge = "yes", condition = function(df) df[df$father_cured == 1,])
father_disease_no <- disease$AddChild("Father Disease No", label = "Father Disease", edge = "no", condition = function(df) df[df$person_disease == 0,])
#data filter (pre-order)
#an alternative would be to do this recursively
disease$Do(function(node) {
for (child in node$children) {
child$data <- child$condition(node$data)
}
})
print(disease, total = function(node) nrow(node$data))
#plotting
#(many more options are available, see ?plot.Node)
SetEdgeStyle(disease,
fontname = "helvetica",
arrowhead = "none",
label = function(node) paste0(node$edge, "\n", "total = ", nrow(node$data)))
SetNodeStyle(disease,
fontname = "helvetica",
label = function(node) node$label)
plot(disease)
关于r - 如何在 R 中直观地将具有多个变量的列联表表示为决策树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062585/
我是一名优秀的程序员,十分优秀!