0

我正在使用 Expss 包在 R 中创建表格。我有 5 个语句,每个语句有 5 个品牌。5 个语句在 5 个连续变量中,例如 a1、a2、a3、a4、a5 我可以有如下表格格式的表格吗?

在此处输入图像描述

4

1 回答 1

0

有两种解决方案:一是冗长但不可扩展,二是可扩展但不是很简单。这两种解决方案都基于我们将标签从变量重新定位到横幅位置的想法。

    library(expss)
    # create sample of data
    set.seed(123)
    N = 150
    df = data.frame(
        st1 = sample(paste0("brand", 1:5), N, replace = TRUE),
        st2 = sample(paste0("brand", 1:5), N, replace = TRUE),
        st3 = sample(paste0("brand", 1:5), N, replace = TRUE),
        st4 = sample(paste0("brand", 1:5), N, replace = TRUE),
        st5 = sample(paste0("brand", 1:5), N, replace = TRUE)
    ) %>% apply_labels(
                       st1 = 'Statement 1', 
                       st2 = 'Statement 2', 
                       st3 = 'Statement 3', 
                       st4 = 'Statement 4', 
                       st5 = 'Statement 5' 
                       )

    # verbose solution with Tab_*. It is not scalable for large number of variables 
    # manipulation with variable labels is needed to repostion variable labels from rows to column
    df %>% 
        tab_total_row_position("above") %>% 
        tab_cells("|" = drop_var_labs(st1)) %>%
        tab_stat_cpct(label = var_lab(st1)) %>% 
        tab_cells("|" = drop_var_labs(st2)) %>% 
        tab_stat_cpct(label = var_lab(st2)) %>% 
        tab_cells("|" = drop_var_labs(st3)) %>% 
        tab_stat_cpct(label = var_lab(st3)) %>% 
        tab_cells("|" = drop_var_labs(st4)) %>% 
        tab_stat_cpct(label = var_lab(st4)) %>% 
        tab_cells("|" = drop_var_labs(st5)) %>%
        tab_stat_cpct(label = var_lab(st5)) %>% 
        tab_pivot(stat_position = "inside_columns")  %>% 
        tab_transpose() 

    # solution wich will work for arbirary number of variables
    df %>% 
        calculate(
            lapply(st1 %to% st5, function(item)
                # manipulation with variable labels is needed to repostion variable labels from rows to column
                cro(list(drop_var_labs(item)), list(var_lab(item)), total_row_position = "above")
            )
        ) %>% 
        Reduce("%merge%", .) %>% 
        tab_transpose()
于 2018-12-17T12:25:55.157 回答