使用Likert包在R中创建不同堆积条形图的问题

时间:2014-06-12 22:20:10

标签: r stacked-chart

使用R中的Likert包,我试图创建不同的堆积条形图来比较调查项目的响应,其中受访者根据两个尺度对每个项目进行评分:重要性和有效性(1到5,带有"不能判断每个人的选项。对于每个项目,我将情节集中在" 3"类别,图表最右侧的4和5个响应的百分比,以及最左侧3个响应的响应百分比。我试图包括一个例子,但我是新手,服务条款不允许我这样做。

当有两个以上级别时,我的R代码正常工作。但是,当少于3个级别时,我会遇到问题。

这是一个最小的例子:

Importance <- c(4,5,5,5,4,4)
Effectiveness <- c(5,4,4,4,5,5)
df <- data.frame(Importance,Effectiveness)
df

levels = c("Cannot Judge", "1", "2", "3", "4", "5")

df$Importance <- recode(df$Importance, from=c(0,1,2,3,4,5), to=c("Cannot Judge", "1", "2", "3", "4", "5"))
df$Importance <- as.factor(df$Importance)
df$Importance <- factor(df$Importance, levels=c("Cannot Judge", "1", "2", "3", "4", "5"), ordered=TRUE)
df$Effectiveness <- recode(df$Effectiveness, from=c(0,1,2,3,4,5), to=c("Cannot Judge", "1", "2", "3", "4", "5"))
df$Effectiveness <- as.factor(df$Effectiveness)
df$Effectiveness <- factor(df$Effectiveness, levels=c("Cannot Judge", "1", "2", "3", "4", "5"), ordered=TRUE)

df2 <- likert(df)
plot(df2)

这会导致以下错误:

Error in matrix(value, n, p) : 
  'data' must be of a vector type, was 'NULL'

问题似乎是在我将数字数据重新编码为因子后,在data.frame上调用likert()命令时。如果我不重新编码因子,只是将likert()应用于原始数据,则会生成绘图,但它会自动居中于4到5之间(在此数据集中),这不是我需要的。

我认识到这些因素最好是&#34;非常重要&#34;,&#34;重要&#34;,&#34;非常有效&#34;,&#34;有效&#但是,由于两个尺度不同,我不知道在不保持1-5方案的情况下比较两个尺度的另一种方法。

为什么我得到了

Error in matrix(value, n, p) : 
      'data' must be of a vector type, was 'NULL'?

如何调整我的代码以使其适用于两个级别?

提前致谢。

2 个答案:

答案 0 :(得分:3)

您收到此错误,因为您没有“低结果”值。 likert.bar.plot函数使用ggplot并为正响应和否定响应创建一个图层,但是,它不会先检查这些组中是否有任何观察结果。当它添加一个空的图层时,您会收到上面的错误消息。

我发现消除错误的最简单方法,原始图是手动删除坏图层。您可以使用

执行此操作
df2 <- likert(df)
pp <- plot(df2)
pp$layers <- pp$layers[-2]

(至少在这种情况下它是第2层;如果您设置其他可能不同的选项,那么您可能需要尝试其他值)

likert bar plot

答案 1 :(得分:0)

使用您的原始data.frame,这是一种算法方法,可以在绘制的问题集完全缺失值时删除左侧或右侧堆叠条形图层...

Importance <- c(4,5,5,5,4,4)
Effectiveness <- c(5,4,4,4,5,5)
df <- data.frame(Importance,Effectiveness)
df

levels = c("Cannot Judge", "1", "2", "3", "4", "5")

df$Importance <- recode(df$Importance, from=c(0,1,2,3,4,5), to=c("Cannot Judge", "1", "2", "3", "4", "5"))
df$Importance <- as.factor(df$Importance)
df$Importance <- factor(df$Importance, levels=c("Cannot Judge", "1", "2", "3", "4", "5"), ordered=TRUE)
df$Effectiveness <- recode(df$Effectiveness, from=c(0,1,2,3,4,5), to=c("Cannot Judge", "1", "2", "3", "4", "5"))
df$Effectiveness <- as.factor(df$Effectiveness)
df$Effectiveness <- factor(df$Effectiveness, levels=c("Cannot Judge", "1", "2", "3", "4", "5"), ordered=TRUE)

df.likert <- likert(df)   

# This is the proposed fix
LHS <- 2 # layer number for SD D or equiv
RHS <- 3 # layer number for A SA or equiv
pp <- plot(df.likert)
if (sum(is.na(pp$layers[[LHS]]$data$Item)) > 0) pp$layers <- pp$layers[-LHS]
if (sum(is.na(pp$layers[[RHS]]$data$Item)) > 0) pp$layers <- pp$layers[-RHS]
pp