Search code examples
rexpss

How to reorder/reverse the rows of a contingency table generated by [expss]?


I use expss to generate a contingency table.

rawdata %>% 
  tab_cells(A1) %>% 
  tab_cols(total(), R4) %>% 
  tab_stat_cpct() %>% 
  tab_pivot() %>% 
  if_na(0)

A1's values and labels are:

1 Dislike very much
2 Dislike
3 Neither
4 Like
5 Like very much

R4 is for gender.

Therefore, in the output the row order is from "Dislike very much" to "Like very much" (with value 1 to 5).

#Total Male Female
Product liking Dislike very much 0.0 0.0 0.0
Dislike 0.1 0.2 0.0
Neither 4.4 5.4 3.5
Like 53.1 51.4 54.6
Like very much 42.4 43.0 41.9
#Total cases 892.0 407.0 485.0

However, I hope it could be shown form "Like very much" to "Dislike very much" (with value 5 to 1), like:

#Total Male Female
Product liking Like very much 42.4 43.0 41.9
Like 53.1 51.4 54.6
Neither 4.4 5.4 3.5
Dislike 0.1 0.2 0.0
Dislike very much 0.0 0.0 0.0
#Total cases 892.0 407.0 485.0

In the spss, there is a button to decide the ascending or descending order, but I did not find any in the expss.

I have tried the "tab_sort_desc()" but it seems to order the rows based on the specific columns' value rather than value of row label. I tried others but still failed.

Hope anyone could help me out with this question, thank you!


Solution

  • It seems, the simplest way is to recode your variables in an opposite direction:

    rawdata %>%
        let(
            # labels also recoded automatically
            # in this example we recode range of variables
            (A1 %to% A10) := rec(A1 %to% A10, from_to(1:0, 0:1), TRUE ~ copy)    
        ) %>% 
        tab_cells(A1) %>% 
        tab_cols(total(), R4) %>% 
        tab_stat_cpct() %>% 
        tab_pivot() %>% 
        if_na(0)