Crosstab with multiple items

前端 未结 7 965
天命终不由人
天命终不由人 2021-02-01 10:48

In SPSS, it is (relatively) easy to create a cross tab with multiple variables using the factors (or values) as the table heading. So, something like the following (made up dat

7条回答
  •  隐瞒了意图╮
    2021-02-01 11:13

    The underlying issue is that this data is not in tidy format. Crosstabbing multiple variables will be easier when the data is reshaped into "long" form. We can do that with gather from the tidyr package.

    After reshaping, many crosstab functions will work; I'll use tabyl from the janitor package (since - full disclosure - I maintain that package and built the function for this purpose).

    # Create reproducible sample data
    set.seed(1)
    possible_values <- c("1 (Very Often)", "2 (Rarely)", "3 (Never)")
    some_values <- sample(possible_values, 100, replace = TRUE)
    dat <- data.frame(Q1 = some_values[1:25], Q2 = some_values[26:50], 
                     Q3 = some_values[51:75], Q4 = some_values[76:100])
    
    library(tidyr)
    library(janitor)
    
    dat %>%
      gather(question, response) %>% 
      tabyl(question, response)
    #>   question 1 (Very Often) 2 (Rarely) 3 (Never)
    #> 1       Q1              8          8         9
    #> 2       Q2              4         11        10
    #> 3       Q3              8         12         5
    #> 4       Q4              7          7        11
    

    From there, you can format with functions like janitor::adorn_percentages().

提交回复
热议问题