首页 > 解决方案 > completing tables in paired designs with missing levels

问题描述

I have a repeated measures design with categorical variables. Let's say, participants reported their attitude ('Approve', 'Neutral', 'Disapprove') at time point 1 and 2. I then create a table with frequencies of response combinations.

# setup
set.seed(123)
library(tidyverse)

# made-up data
survey.data <- data.frame(
  `1st survey` = c('Approve', 'Approve', 'Neutral', 'Approve'),
  `2nd survey` = c('Approve', 'Disapprove', 'Approve', 'Neutral'),
  `Counts` = c(79, 15, 86, 10),
  check.names = FALSE
) %>%
tidyr::uncount(., Counts) %>%
  tibble::as_tibble()

# table of counts
table("1" = survey.data$`1st survey`, "2" = survey.data$`2nd survey`)
#>          2
#> 1         Approve Disapprove Neutral
#>   Approve      79         15      10
#>   Neutral      86          0       0

Note here that since nobody chose the option "Disapprove" at time point-1, it is missing from the table. This is, of course, expected. But the function I want to use (rcompanion::cohenG) expects an equal number of rows and columns in a table. So I was wondering how I can change the code above to get the expected output here-

#>          2
#> 1         Approve Disapprove Neutral
#>   Approve      79         15      10
#>   Disapprove    0          0       0 
#>   Neutral      86          0       0

标签: r

解决方案


You can cast the responses to factors with three known levels

levels <- c("Disapprove", "Neutral", "Approve")

survey.data <- survey.data %>%
  mutate_at(vars(`1st survey`,
                 `2nd survey`),
            factor, levels = levels)

table(survey.data$`1st survey`,
      survey.data$`2nd survey`)
#>             
#>              Disapprove Neutral Approve
#>   Disapprove          0       0       0
#>   Neutral             0       0      86
#>   Approve            15      10      79

Created on 2019-03-08 by the reprex package (v0.2.1)


推荐阅读