R中的网格表格式

时间:2018-12-14 13:52:22

标签: r expss

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

enter image description here

1 个答案:

答案 0 :(得分: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()