首页 > 解决方案 > 因子水平重复时锁定因子水平顺序

问题描述

我试图锁定变量的因子级别顺序,以使结果以与数据框相同的顺序显示在图中。

datad$outcome <- factor(data$outcome, levels = unadjusted.combined$outcome)

当某些行重复时,有没有办法解决此顺序:我的行重复,因为我有两种不同度量的结果,这会产生错误:

Error in `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  : factor level [54] is duplicated

我的数据看起来像这样;

xvar   outcome
x1     wt_2
x1     wt_3
x1     wt_4
x1     bmi_2
x1     bmi_3  
x1     bmi_4
x2     wt_2
x2     wt_3
x2     wt_4
x2     bmi_2
x2     bmi_3  
x2     bmi_4

最后,我的情节如下:(目前结果按字母顺序排列)

ggplot(data=data, aes(x=outcome, y=estimate, ymin=lci, ymax=uci, colour=xvar)) +  geom_pointrange() + geom_hline(yintercept=0, lty=2) + coord_flip()

标签: rggplot2data-manipulation

解决方案


这是一个答案的尝试。根据您的问题,您希望结果遵循原始数据的顺序,而不是默认的字母顺序。
以下是一些示例数据:

data<-structure(list(xvar = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 
                      2L, 2L, 2L, 2L, 2L), .Label = c("x1", "x2"), class = "factor"), 
           outcome = structure(c(4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 
                     1L, 2L, 3L), .Label = c("bmi_2", "bmi_3", "bmi_4", "wt_2", 
                      "wt_3", "wt_4"), class = "factor"), estimate = c(10.40, 
                       11.24, 10.09, 14.64, 10.48, 8.71, 13.27, 8.87, 9.97, 
                       13.12, 12.17, 8.44)), row.names = c(NA, 
                                          -12L), class = "data.frame")

xvar和都outcome默认为因子。如果我们运行 ggplot plot 命令:

ggplot(data=data, aes(x=outcome, y=estimate,  colour=xvar, ymin=0, ymax=15)) +  
  geom_pointrange() + geom_hline(yintercept=0, lty=2) #+ coord_flip()

x 轴按字母顺序排列:
在此处输入图像描述

现在为了保留原始顺序,我们可以在 factor 函数中使用 ordered=TRUE 选项。使用正确的顺序传递levels=

#order the factors in the order they appear in the data frame
data$outcome <- factor(data$outcome, levels= unique(data$outcome), ordered=TRUE)

ggplot(data=data, aes(x=outcome, y=estimate,  colour=xvar, ymin=0, ymax=15)) +  
  geom_pointrange() + geom_hline(yintercept=0, lty=2) #+ coord_flip()

现在我们保持正确的顺序。 在此处输入图像描述

这是您的问题变得模糊的地方。如果要以相同的顺序绘制 x1 然后 x2 的结果,则需要通过 paste(data$xvar, data$outcome) 创建一个新变量,然后将此新变量用作 x 轴。

希望这能回答你的问题。


推荐阅读