crosstable()导出到csv

时间:2016-08-04 19:43:54

标签: r contingency

你好,所以我需要做一个交叉。我发现有多种方法,但是这个函数使得表格就像Excel中的数据透视表一样。它工作得很完美但是我不能将它导出到csv或excel,因为它是“Crosstable”类,所以它不能被强制。

如何设法将其导出到csv?

参见此示例

#This way you activate the library
source("http://pcwww.liv.ac.uk/~william/R/crosstab.r")

# Creating the database

ID <- seq(1:177)
Age <- sample(c("0-15", "16-29", "30-44", "45-64", "65+"), 177, replace = TRUE)
Sex <- sample(c("Male", "Female"), 177, replace = TRUE)
Country <- sample(c("England", "Wales", "Scotland", "N. Ireland"), 177, replace = TRUE)
Health <- sample(c("Poor", "Average", "Good"), 177, replace = TRUE)
Survey <- data.frame(Age, Sex, Country, Health)


#It resulted in this

     Age    Sex    Country  Health
## 1 16-29   Male   Scotland    Good
## 2   65+ Female      Wales Average
## 3  0-15   Male      Wales    Poor
## 4 16-29   Male N. Ireland Average
## 5 30-44 Female      Wales    Good
## 6 30-44 Female      Wales Average

然后我想要年龄与性交叉表

# Frequency count
ct <- crosstab(Survey, row.vars = "Age", col.vars = "Sex", type = "f")

#getting this

##       Sex Female Male Sum
## Age                      
## 0-15          19   20  39
## 16-29         11   14  25
## 30-44         23   17  40
## 45-64         15   19  34
## 65+           20   19  39
## Sum           88   89 177

最后,当每个人都在完美地工作时,我得到以下信息

 # Save file as csv
write.csv(ct,"ct.csv")

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
cannot coerce class ""crosstab"" to a data.frame

您可以在此网站上找到有关该功能的更多信息:

http://rstudio-pubs-static.s3.amazonaws.com/6975_c4943349b6174f448104a5513fed59a9.html

2 个答案:

答案 0 :(得分:0)

write.csv:要写入的对象,最好是矩阵或数据帧。如果不是,则尝试将x强制转换为数据帧。所以一个解决方案是:

write.csv(ct$table,"ct.csv")

答案 1 :(得分:0)

您可以添加以下代码行来转换class&#34; crosstab&#34;进入Matrix然后将其写入csv

ct <- crosstab(Survey, row.vars = "Age", col.vars = "Sex", type = "f")

# Convert 'ct' into a Matrix type
ct_mtrx <- descr:::CreateNewTab(ct)

# Write the file into a csv file
write.csv(ct_mtrx,"ct.csv")