gpt4 book ai didi

r - crosstable() 导出到 csv

转载 作者:行者123 更新时间:2023-12-04 17:57:59 25 4
gpt4 key购买 nike

你好,所以我需要制作一个交叉表。我发现有多种方法,但有一个函数使表格就像 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

最佳答案

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

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

关于r - crosstable() 导出到 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com