You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言生成Likert图报错:dimnames长度与数组范围不匹配

问题:Likert图生成报错Error: length of 'dimnames' [2] not equal to array extent from as.data.frame

此前代码可正常生成数十个Likert量表可视化,今日运行旧代码(未修改原Excel文件)时触发上述错误。

使用代码

library(ggplot2)
library(readxl)
library(tidyverse)
library(HH)

thesis <- read_excel("C:/Users/aarde/Desktop/Thesis_scrubbed.xlsx",sheet = "Gamer Data",range = "K1:M8")

names(thesis) <- c("Q10. More Scenarios","Q18. Play Again?", "Q20. More Code Orange")
thesis$`Q10. More Scenarios` = factor(thesis$`Q10. More Scenarios` , levels = c("1 - Strongly Disagree", "2 - Disagree", "3 - Neutral", "4 - Agree", "5 - Strongly Agree"), ordered = TRUE)
thesis$`Q18. Play Again?` = factor(thesis$`Q18. Play Again?`, levels = c("1 - Strongly Disagree", "2 - Disagree", "3 - Neutral", "4 - Agree", "5 - Strongly Agree"), ordered = TRUE)
thesis$`Q20. More Code Orange` = factor(thesis$`Q20. More Code Orange`, levels = c("1 - Strongly Disagree", "2 - Disagree", "3 - Neutral", "4 - Agree", "5 - Strongly Agree"), ordered = TRUE)
thesis <- as.data.frame(thesis)
#thesis <- subset(thesis, select = -NA)

thesisLikert = likert(thesis)

p <- likert::likert.bar.plot(thesisLikert, group.order = names(thesis), center = 3)
p + labs(title = "Future Expansion", subtitle = "Gamers", x = "Questions", y = "Percentage Response")

已执行排查步骤

  • 验证Excel数据范围正确,无NA/NAN响应
  • 验证thesis对象、dimnames(2)及length(names(thesis))长度一致
  • 移除labs代码并尝试子集化数据,问题未解决

已知信息

  • Excel数据读取正确
  • 转换为data.frame前thesis数据无误
  • names(thesis)内容正确

dput(thesis)输出

structure(list(`Q10. More Scenarios` = structure(c(5L, 3L, 4L, 
5L, 5L, 4L, 4L), levels = c("1 - Strongly Disagree", "2 - Disagree", 
"3 - Neutral", "4 - Agree", "5 - Strongly Agree"), class = c("ordered", 
"factor")), `Q18. Play Again?` = structure(c(5L, 2L, 4L, 5L, 
5L, 5L, 4L), levels = c("1 - Strongly Disagree", "2 - Disagree", 
"3 - Neutral", "4 - Agree", "5 - Strongly Agree"), class = c("ordered", 
"factor")), `Q20. More Code Orange` = structure(c(5L, 3L, 3L, 
4L, 4L, 5L, 5L), levels = c("1 - Strongly Disagree", "2 - Disagree", 
"3 - Neutral", "4 - Agree", "5 - Strongly Agree"), class = c("ordered", 
"factor"))), row.names = c(NA, -7L), class = "data.frame")

问题原因与解决方法

原因

同时加载的HH和likert包均包含likert()函数,但二者对输入数据的处理逻辑不一致。当前代码中thesisLikert = likert(thesis)调用的是HH包的likert()函数,该函数的参数要求与后续绘图用的likert::likert.bar.plot不匹配,导致维度错误。

解决方法

修改代码中调用likert()函数的部分,明确指定使用likert包的版本:

# 替换原有的 thesisLikert = likert(thesis)
thesisLikert = likert::likert(thesis)

修改后重新运行代码即可正常生成Likert图。

内容的提问来源于stack exchange,提问作者Aarden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:22:53