1

在生成列联表时,我使用CrossTableR 中的函数,因为它是我设法找到的信息量最大且最灵活的函数,它可以立即为您提供很多东西,而无需单独计算。但是,它生成的输出是文本输出,主要针对 R 中的控制台。这对我来说是一个大问题,因为我依靠输出这些类型的表格来在下一步分析中表现出色。

有没有办法将输出CrossTable输出到 Excel 电子表格,以便每个数字都在自己的单元格中?(即,不是完全进入单个单元格的文本)(“文本到列”没有帮助)

4

2 回答 2

1

我编写了一个将交叉表转换为 excel 文件的函数。也许它对其他人也有用:

#writes output from gmodels::CrossTable to an excel file
#package "xlsx" should be installed
crossExcel <- function(Cross.Table, file, chi=F) {  
  Cross.Table <- x
  
  t <- reshape(as.data.frame(Cross.Table[["t"]]), idvar="x", timevar="y", direction="wide")
  row <- reshape(as.data.frame(Cross.Table[["prop.row"]]), idvar="x", timevar="y", direction="wide")
  col <- reshape(as.data.frame(Cross.Table[["prop.col"]]), idvar="x", timevar="y", direction="wide")
  tbl <- reshape(as.data.frame(Cross.Table[["prop.tbl"]]), idvar="x", timevar="y", direction="wide")
  
  xlsx::write.xlsx(t, file=file, sheetName="t", row.names=F)
  xlsx::write.xlsx(row, file=file, sheetName="prop.row", append=T, row.names=F)
  xlsx::write.xlsx(col, file=file, sheetName="prop.col", append=T, row.names=F)
  xlsx::write.xlsx(tbl, file=file, sheetName="prop.tbl", append=T, row.names=F)
  
  if (chi==T) {
    exp <- as.data.frame(x[["chisq"]][["expected"]])
    xlsx::write.xlsx(exp, file=file, sheetName="exp", append=T, row.names=T)
    
    t <- t[ ,2:3]
    chip <- ((exp-t)*(exp-t))/exp
    xlsx::write.xlsx(chip, file=file, sheetName="prop.chisq", append=T, row.names=T)
  }
  
  print(paste0("CrossTable exported to ", getwd() ,file))
}

如何使用它的示例:

data(infert, package = "datasets") #obtaining exapmle data
x <- gmodels::CrossTable(infert$education, infert$induced) 
crossExcel(x, "output.xlsx")
于 2021-10-14T22:21:20.827 回答
0
# obtaining data
library('gmodels')
data(infert, package = "datasets")
# asign the result to object
d <- CrossTable(infert$education, infert$induced, expected = TRUE)
# now you can use d object to build something you could save using
# `write.table` to csv or directly to xlsx by other methods

# use str(d) to study structure of returned object
str(d)
于 2017-07-04T10:47:24.350 回答