Reputation:
I am trying to create a 3 way table using R.
I have used the below code in summarizing the data and coming up with a 3 way table
3waydata <- data %>% group_by(duration, education, sex) %>%
summarise(count = sum(number))
And then come up with the following table
with(3waydata, table(duration, sex, education)
However I'm not sure how to include the counts within the table. I have the structure I want but am unsure how to include the counts within the table.
education high low medium unknown
duration sex
five-to-ten-years female 1 1 1 1
male 1 1 1 1
five-years-or-less female 1 1 1 1
male 1 1 1 1
more-than-ten-years female 1 1 1 1
male 1 1 1 1
native-born female 1 1 1 1
male 1 1 1 1
unknown female 1 1 1 1
male 1 1 1 1
Upvotes: 0
Views: 75
Reputation: 173803
To get the table you want, you can use xtabs
and ftable
:
with(`3waydata`, ftable(xtabs(count ~ duration + sex + education)))
#> education high low medium unknown
#> duration sex
#> five-to-ten-years F 8 0 10 0
#> M 0 9 12 11
#> five-years-or-less F 10 10 0 9
#> M 9 14 15 12
#> more-than-ten-years F 22 26 29 10
#> M 0 12 31 0
#> native-born F 0 0 11 0
#> M 12 0 0 0
#> unknown F 0 13 0 0
#> M 0 12 15 11
Obviously, I had to create my own data since you did not supply your own. Please note that 3waydata
is not a valid variable name in R, so has no be wrapped in quotes.
set.seed(69)
data <- data.frame(education = sample(c("high","low","medium","unknown"), 30, T),
sex = rep(c("M", "F"), 15),
duration = sample(c("unknown", "native-born",
"five-years-or-less", "five-to-ten-years",
"more-than-ten-years"), 30, T),
number = rpois(30, 10))
`3waydata` <- data %>%
group_by(duration, education, sex) %>%
summarise(count = sum(number))
Upvotes: 1