如何将SPSS(sav)数据转换为适配HH::likert的格式?
Tidyverse 解决方案
通过宽转长→标签映射→长转宽的三步流程即可完成格式转换,代码如下:
library(tidyverse) # 原数据集 cheeses <- tribble( ~Cheddar, ~Brie, ~Stilton, 1, 4, 2, 2, 4, 1, 1, 1, 3, 4, 1, 5, 3, 2, 4, 5, 3, 1, 1, 5, 2 ) # 格式转换 cheeseslikert <- cheeses %>% # 把每款奶酪的评分拆分为行数据 pivot_longer(everything(), names_to = "Question", values_to = "rating") %>% # 将数字评分映射为对应文本标签 mutate(rating_label = case_when( rating == 1 ~ "Strongly like", rating == 2 ~ "Like", rating == 3 ~ "Unsure", rating == 4 ~ "Dislike", rating == 5 ~ "Strongly dislike" )) %>% # 按奶酪和标签统计响应数量 count(Question, rating_label) %>% # 把标签转为列,缺失的评分项填充0 pivot_wider(names_from = rating_label, values_from = n, values_fill = 0) %>% # 调整列顺序,匹配目标格式 select(Question, "Strongly like", "Like", "Unsure", "Dislike", "Strongly dislike") # 查看转换结果 cheeseslikert
Base R 解决方案
无需依赖tidyverse,用基础函数也能实现:
# 原数据集 cheeses <- tribble( ~Cheddar, ~Brie, ~Stilton, 1, 4, 2, 2, 4, 1, 1, 1, 3, 4, 1, 5, 3, 2, 4, 5, 3, 1, 1, 5, 2 ) # 将宽格式转为长格式 long_data <- stack(cheeses) colnames(long_data) <- c("rating", "Question") # 统计交叉频数 freq_table <- table(long_data$Question, long_data$rating) # 转换为数据框并调整格式 cheeseslikert_base <- as.data.frame.matrix(freq_table) cheeseslikert_base$Question <- rownames(cheeseslikert_base) colnames(cheeseslikert_base) <- c("Strongly like", "Like", "Unsure", "Dislike", "Strongly dislike", "Question") cheeseslikert_base <- cheeseslikert_base[, c("Question", "Strongly like", "Like", "Unsure", "Dislike", "Strongly dislike")] # 查看转换结果 cheeseslikert_base
验证绘图
转换完成后,直接使用你提供的代码即可生成正确的Likert图:
library(HH) HH::likert(Question~., cheeseslikert, positive.order=TRUE, as.percent = TRUE, main="Cheese preferences.", xlab="percentage", ylab="" )
内容的提问来源于stack exchange,提问作者donnek
相关产品推荐
相关产品推荐

