0

I have been trying to create a contingency table in R with percentage distribution of education for husbands (6 category) and wives (6 category) BY marriage cohort (total 4 cohorts). My ideal is something like this: IdealTable.

However, what I have been able to get at max is: CurrentTable.

I am not able to figure out how to convert my row and column sums to percentages (similar to the ideal). The current code that I am using is:

three.table = addmargins(xtabs(~MarriageCohort + HerEdu + HisEdu, data = mydata))

ftable(three.table)
  1. Is there a way I can turn the row and column sums into percentages for each marriage cohort?
  2. How can I add labels to this and export the ftable?

I am relatively new to R and tried to find solutions to my questions above on google, but havent been successful. Posting my query on this platform for the first time and any help with this will be greatly appreciated! Thank you!

jrcalabrese
  • 2,184
  • 3
  • 10
  • 30
  • Welcome to SO! Please make your post [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by providing your dataset using `dput(mydata)`. Also please avoid posting images of code/data. – jrcalabrese Nov 21 '22 at 01:58

1 Answers1

0

One approach would be to create separate xtab runs for each MarriageCohort:

Cohorts <- lapply( mydata, mydata["MarriageCohort"], 
                              function(z) xtabs( ~HerEdu + HisEdu, data = z) )

Then get totals in each Cohorts item before dividing the cohort addmargins(.) result by those totals and multiplying by 100 to get percent values:

divCohorts <- lapply(Cohorts, function(tbl) 100*addmargins(tbl)/sum(tbl) )

Then you will need to clean those items up to your desires. You have not included data so the cleanup remains your responsibility. (I did not use sapply because that could give you a big matrix that might be difficult to manage, but you could try it and see if you in the second stepwere satisfied with that approach.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487