r - 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
解决方案
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)
推荐阅读
- java - Java 使用带有 javax.sound.sampled.Clip 的 mp3、ogg 和 wav 文件(或获取声音文件的比特率)
- sql - 基于变量有条件地检索数据
- java - 我为这个计划编写了一个程序,但我想知道程序是否有任何答案和我的写作不同?
- c# - C# 将联系人同步到 AD 的最佳方法
- python - 执行批量插入 SQLAlchemy 的最佳方法
- reactjs - 通过改变反应状态来更改反应传单层网址会引发错误-> TypeError:无法读取未定义的属性“调用”
- mysql - 查找sql中每个不同行的最大计数
- wordpress - 根据在 WooCommerce 中选择的数量和选项显示可变产品的总价格和总重量
- postgresql - postgres 优化范围搜索查询
- javascript - 如何使热图图表上的颜色以比例值显示?