Search code examples
rcontingency

"Nested" relative frequency in 3 way flat contingecy table (ftable)


I am wondering whether there is a direct way to get nested relative frequencies in a 3-way flat (!) contingency table.

N    <- 10
(sex <- factor(sample(c("f", "m"), N, replace=TRUE)))
(work <- factor(sample(c("home", "office"), N, replace=TRUE)))
(satisfaction <- factor(sample(c("excellent", "ok","bad"), N, replace=TRUE)))
ftable(work, sex, satisfaction, row.vars=c("sex", "satisfaction"))

This code produces this output:

                work home office
sex satisfaction                 
f   bad                  1      1
    excellent            0      1
    ok                   1      1
m   bad                  1      0
    excellent            1      0
    ok                   1      2

What I would like to get is

                work home office
sex satisfaction                 
f   bad                  0.2      0.2
    excellent            0        0.2
    ok                   0.2      0.2
m   bad                  0.2      0
    excellent            0.2      0
    ok                   0.2      0.4

I am aware that i can calculate tables with prop.table but haven't figured out how this could be combined with flat contingency tables as produced by ftable. There is certainly a way to calculate the relative frequencies separately for each sex - group, but I am interested in a more direct way. So far I haven't found any way how to get relative frequencies into flat contingency tables.

Note: In this example male and female groups have the same size (5); however, the solution I am looking for should be flexible enough so that groups can also have different sizes.

Many thanks!


Solution

  • Perhaps you can consider starting with table, then using prop.table wrapped in ftable:

    y <- table(sex, satisfaction, work)
    y
    # , , work = home
    # 
    #    satisfaction
    # sex bad excellent ok
    #   f   1         1  0
    #   m   1         1  1
    # 
    # , , work = office
    # 
    #    satisfaction
    # sex bad excellent ok
    #   f   0         1  1
    #   m   0         1  2
    
    ftable(prop.table(y, margin=3))
    #                  work home office
    # sex satisfaction                 
    # f   bad                0.2    0.0
    #     excellent          0.2    0.2
    #     ok                 0.0    0.2
    # m   bad                0.2    0.0
    #     excellent          0.2    0.2
    #     ok                 0.2    0.4
    

    This is assuming we start with something like this:

    set.seed(1)
    N <- 10
    sex <- factor(sample(c("f", "m"), N, replace=TRUE))
    work <- factor(sample(c("home", "office"), N, replace=TRUE))
    satisfaction <- factor(sample(c("excellent", "ok","bad"), N, replace=TRUE))
    

    Similarly, if you already have an ftable (let's call it "x"), you can try:

    ftable(prop.table(as.table(x), margin=3))