Search code examples
rsurvey

Labelling tables made with survey package from list of names


I created a list of variables to describe as well as a list of corresponding variable/row names. The function works fine when not assigning labels, but I am struggling with how to label table rows when looping over a list.

My data and design:

library(survey)
df <- data.frame(id=1:5, a=c(0,1,1,1,0), b=c(0,1,1,1,NA), c=c(0,0,0,1,1), d=c(0,0,1,0,1), 
e=c(0,1,0,0,1),weight=c(1,0.2,3, 0.5, 0.8))
df
group1 <- c("a", "b")
group2 <- c("c", "d", "e")
groups <- list(group1, group2)

labels_ab <- c("label for group a", "label for group b")
labels_cde <- c("label for group c", "label for group d", "label for group e")
labels_list <- list(labels_ab, labels_cde)

design <- svydesign(id=~1, weights=~weight, data=df)

My attempt:

 # function that binds table rows
    make_table <- function(columns, row_names) {
    mat <- matrix(ncol=2) # create empty matrix with two columns
    for(i in seq_along(columns)) {
    formula <- as.formula(paste("~",columns[i])) # formula for given column
    tab2 <- prop.table(svytable(formula, design))*100 # create table for given column
    mat <- rbind(mat, tab2) #bind individual rows to matrix 
     }
    mat2 <- mat[-1,] # remove first NA row
    rownames(mat2) <- row_names # NOT WORKING: assign labels to rows
    print(kable(mat2)) 
    }

    x <- lapply(groups, make_table, row_names=labels_list)

Solution

  • You are supplying labels_list directly as a list, not within lapply, so it's taking each element of labels_list as a row name. You can just use mapply to apply over multiple lists.

    x <- mapply(make_table, groups, labels_list)