r - 基于查找表使用 dplyr 重新编码矩阵值
问题描述
我有一个矩阵,其中包含许多案例和问卷中的相应答案。下面的强简化示例 (raw_responses) 包含 5 个人对 5 个项目的答案。让我们假设这些是多项选择项,每个选项有 4 个可能的答案。如果该项目未处理,则此人收到代码 9。
raw_responses <- data.frame('id' = 1:10,
'item_1' = sample(c(1:4,9), 10, replace = TRUE),
'item_2' = sample(c(1:4,9), 10, replace = TRUE),
'item_3' = sample(c(1:4,9), 10, replace = TRUE),
'item_4' = sample(c(1:4,9), 10, replace = TRUE),
'item_5' = sample(c(1:4,9), 10, replace = TRUE))
正确答案存储在反映整个测试设计的单独表中。下面又是一个强烈简化的变体(设计),只有项目名称和相应的正确答案。
design <- data.frame('item' = c('item_1','item_2','item_3','item_4','item_5'),
'key' = sample(1:4, 5, replace = TRUE))
最后,目标是一个带有得分答案的表格。正确答案用 1 编码,错误答案用 0 编码,“空”答案用 99 编码。例如,这适用于下面的 for 循环。
scored_responses <- raw_responses
for(item in colnames(raw_responses)[2:6]) {
scored_responses[, item] <- ifelse(scored_responses[, item] == design[design$item == item, 'key'], 1,
ifelse(scored_responses[, item] == 9, 99, 0))
}
但是,我想知道这是否可以与 dplyr(包括 case_when)和可能的 purr 一起使用更有效的变体。特别是因为在更长的 dplyr 管道的帮助下清理了非常广泛的答案表,如果可以在其中建立评分将是一个优势。
我提前感谢您提供的所有想法和提示。
解决方案
以长格式获取数据,连接,重新编码值并以宽格式获取数据。
library(dplyr)
library(tidyr)
raw_responses %>%
pivot_longer(cols = -id, names_to = 'item') %>%
left_join(design, by = 'item') %>%
mutate(value = case_when(value == 9 ~ 99,
value == key ~ 1,
TRUE ~ 0)) %>%
select(-key) %>%
pivot_wider(names_from = 'item')
# A tibble: 10 x 6
# id item_1 item_2 item_3 item_4 item_5
# <int> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 99 99 1 0 0
# 2 2 99 99 99 0 0
# 3 3 1 99 0 99 99
# 4 4 0 1 1 99 1
# 5 5 99 0 1 0 1
# 6 6 0 1 0 0 1
# 7 7 0 0 0 1 99
# 8 8 1 99 0 0 0
# 9 9 0 99 99 0 1
#10 10 99 1 99 1 0
另一种无需将数据转换为宽格式的方法是使用map2_dfc
from purrr
:
library(purrr)
map2_dfc(raw_responses[-1], design$key, ~case_when(.x == 9 ~ 99,
.x == .y ~ 1,
TRUE ~ 0))
但是,为了使这个答案起作用,我们需要确保列名raw_responses
和列名design$item
的顺序相同。在此示例中,它们已经处于相同的顺序,但是,在实际数据中,如果它们不是,我们可以通过执行以下操作来实现:
raw_responses[-1] <- raw_responses[-1][design$key]
推荐阅读
- python - 如何只保留字符串中的某些字符
- sql-server - SQL Server 中的类型转换问题
- python - GCP 没有名为“tensorflow”的模块
- python - Gurobi 中的简单二次问题没有产生最佳结果?
- c++ - 为什么没有指针就无法打印数组?下面的代码是否正确?
- python - 使用 tkinter 导入带有按钮的数据集
- javascript - HTTP 错误:当我想使用 mxcl/installer nodejs 模块下载 Forge 时出现状态码 404
- string - 制作模型来识别字符串
- android-studio - 位置提供程序间隔的Android问题
- c# - 比较 C# 列表中的值