用名称列表中的调查包制作的标签表

时间:2019-11-19 18:57:58

标签: r survey

我创建了一个变量列表来描述以及相应的变量/行名列表。当不分配标签时,该功能运行良好,但是在遍历列表时如何为表行添加标签却很麻烦。

我的数据和设计:

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)

我的尝试

 # 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)

1 个答案:

答案 0 :(得分:1)

您直接将labels_list作为列表而不是在lapply中提供,因此它将labels_list的每个元素作为行名。您可以只使用mapply来应用多个列表。

x <- mapply(make_table, groups, labels_list)