如何在R中将包含多个变量的列联表以决策树的形式进行可视化?

例如,假设我有一个受访者,我问他/她是否患有某种疾病。从那里,我问他/她的父亲是否也患过这种疾病。如果对后一个问题的回答是肯定的,那么我会问父亲现在是否已经治愈。如果父亲没有患过这种疾病,那么这个问题就不适用。

我可以在R中或其他地方创建这样一个“决策树”吗?

这里有一些可用的数据,其中0表示“否”,1表示“是”:

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)#这里,树是“手动”构建的#然而,根据你的数据和需求,你可能希望直接从数据中生成树#许多这样的例子可以在vignettes中找到,参见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,])#数据过滤(前序遍历)#另一种方法是递归执行disease$Do(function(node) {  for (child in node$children) {    child$data <- child$condition(node$data)  }})print(disease, total = function(node) nrow(node$data))#绘图#(有更多可用的选项,参见?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

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注