从 gmodels 中的 CrossTable 函数制作 corrplot

问题描述

我想使用 gmodels 包中的 Crosstable 函数在我的数据集中评估 2 个二元变量(种族和性别)的卡方统计量,然后使用 corrplot 包可视化残差。这是我在 R 中的代码

#Loading libraries

library(gmodels)

library(corrplot)

#Dataset

Datavisit1<- read_excel("~/Downloads/Datavisit1.xlsx")
Datavisit1 <- structure(list(PATIENTID = c(1548,2371,3843,9573,3352,8590,6217,8503,6610,2783),DX = c("AS","AS","RA","RA"),AGE = c(22,74,18,22,59,45,33,20,32,60),ETH = c(0,1,0),SEX = c(1,1)),row.names = c(NA,-10L),class = c("tbl_df","tbl","data.frame")) 
# replaced the useless call to load an Excel file the we don't have with comment.

#Crosstable

ethsex<- with(Datavisit1,Crosstable(ETH,SEX,prop.r = FALSE,prop.chisq = FALSE,prop.t = FALSE,chisq = TRUE,resid = TRUE,format = "SPSS"))

#Making Corrplot by extracting residuals from prevIoUs step

corrplot(ethsex$residuals,is.corr = FALSE)

我收到错误消息,说我需要矩阵或数据框。有人可以帮助我做错什么吗?本质上,我想得到一个像这样的漂亮图表,但对于 2x2 的情况(种族和性别):

Corrplot graph

先谢谢你!

解决方法

它似乎没有很好的文档记录,但省略 format="SPSS" 参数可以让您得到结果。进一步证明残差是名为“chisq”m 的列表项的子列表

str(ethsex) 
# ... removed a bunch of output lines
 $ chisq     :List of 9
  ..$ statistic: Named num 2.86
  .. ..- attr(*,"names")= chr "X-squared"
  ..$ parameter: Named int 1
  .. ..- attr(*,"names")= chr "df"
  ..$ p.value  : num 0.091
  ..$ method   : chr "Pearson's Chi-squared test"
  ..$ data.name: chr "t"
  ..$ observed : 'table' int [1:2,1:2] 3 4 3 0
  .. ..- attr(*,"dimnames")=List of 2
  .. .. ..$ x: chr [1:2] "0" "1"
  .. .. ..$ y: chr [1:2] "0" "1"
  ..$ expected : num [1:2,1:2] 4.2 2.8 1.8 1.2
  .. ..- attr(*,"dimnames")=List of 2
  .. .. ..$ x: chr [1:2] "0" "1"
  .. .. ..$ y: chr [1:2] "0" "1"
  ..$ residuals: 'table' num [1:2,1:2] -0.586 0.717 0.894 -1.095
  .. ..- attr(*,"dimnames")=List of 2
  .. .. ..$ x: chr [1:2] "0" "1"
  .. .. ..$ y: chr [1:2] "0" "1"
  ..$ stdres   : 'table' num [1:2,1:2] -1.69 1.69 1.69 -1.69
  .. ..- attr(*,"dimnames")=List of 2
  .. .. ..$ x: chr [1:2] "0" "1"
  .. .. ..$ y: chr [1:2] "0" "1"
  ..- attr(*,"class")= chr "htest"

所以这将是消除失败原因后所需的代码:

corrplot(ethsex$chisq$residuals,is.corr = FALSE)

如果您想成为 R 社区的好公民,您可以向软件包维护者发送有关此错误的说明:您可以通过此代码找到他的电子邮件地址。

 maintainer("gmodels")
 #[1] "Gregory R. Warnes <[email protected]>"