gpt4 book ai didi

r - 如何在 R 中直观地将具有多个变量的列联表表示为决策树?

转载 作者:行者123 更新时间:2023-11-30 09:01:04 26 4
gpt4 key购买 nike

例如,假设我有一个受访者,询问他/她是否患有疾病。从那里我问她/他的父亲是否患有这种疾病。如果后一个问题是肯定的,那么我问父亲现在是否痊愈了。如果父亲没有患病,则该问题不适用。

我可以在 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)

enter image description here

最佳答案

您可以使用 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)

enter image description here

关于r - 如何在 R 中直观地将具有多个变量的列联表表示为决策树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com