使用名称列表中的调查包制作的标签表
Labelling tables made with survey package from list of names
我创建了一个变量列表来描述以及相应的 variable/row 名称列表。该函数在不分配标签时工作正常,但我正在努力解决如何在遍历列表时标记 table 行。
我的数据和设计:
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)
您直接将 labels_list
作为列表提供,而不是在 lapply
内提供,因此它将 labels_list
的每个元素作为行名称。您可以只使用 mapply
来应用多个列表。
x <- mapply(make_table, groups, labels_list)
我创建了一个变量列表来描述以及相应的 variable/row 名称列表。该函数在不分配标签时工作正常,但我正在努力解决如何在遍历列表时标记 table 行。
我的数据和设计:
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)
您直接将 labels_list
作为列表提供,而不是在 lapply
内提供,因此它将 labels_list
的每个元素作为行名称。您可以只使用 mapply
来应用多个列表。
x <- mapply(make_table, groups, labels_list)