如何在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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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