r - 因子水平重复时锁定因子水平顺序
问题描述
我试图锁定变量的因子级别顺序,以使结果以与数据框相同的顺序显示在图中。
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()
解决方案
这是一个答案的尝试。根据您的问题,您希望结果遵循原始数据的顺序,而不是默认的字母顺序。
以下是一些示例数据:
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()
现在为了保留原始顺序,我们可以在 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 轴。
希望这能回答你的问题。
推荐阅读
- azure - Azure Microsot.Web/serverFams 与 hostingEnvironments 之间的区别
- mongodb - MongoDB:是否可以以隔离的方式从文档中索引(唯一)子数组?
- python - ImportError:无法从“tensorflow.python.keras.layers.normalization”不匹配版本中导入名称“LayerNormalization”修复?
- javascript - 选中复选框时如何将 AJAX 值发送为 1,未选中时如何发送 0?
- statsmodels - 部分回归图绘制时间过长
- php - php foreach - 尝试 catch,我不知道为什么会出现 500 错误。我打电话给activeMQ
- domain-driven-design - 我应该在哪里做映射?如何在存储库上进行映射?数据源还是存储库?
- calculus - 等距点的阿基米德螺旋代码在中心附近不准确
- azure - 如何在仍然使用 Azure 模板的同时自定义 Azure AD B2C 页面的元素
- flutter - 将带有 RadioListTile 小部件的 AlertDialog 添加到 Flutter 应用程序