Dennis Aguilar
Dennis Aguilar

Reputation: 113

crosstable() export to csv

Hello so i needed to make a crosstable. I found out there were multiple ways, but there was this function that made the table just like a pivot table from Excel. It works perfectly however i cannot export it to csv, or excel,given the fact that is "Crosstable" class, so it cannot be coerced.

How do i manage to export it to a csv?

See this example

#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

but then i wanted the age vs sex cross table

# 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

And finally when everyhing was working perfect i get this following message

 # 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

You can find more information about the function on this website:

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

Upvotes: 3

Views: 6364

Answers (2)

Vijay Kumar
Vijay Kumar

Reputation: 1

You can add the following lines of code to convert class "crosstab" into Matrix and then write it into a 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")

Upvotes: 0

Yong
Yong

Reputation: 1127

write.csv: the object to be written, preferably a matrix or data frame. If not, it is attempted to coerce x to a data frame. So one solution is:

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

Upvotes: 1

Related Questions