如何更改行的顺序?

问题描述 投票:0回答:2

请告知如何控制

flextable
中的行顺序。

例如,在流行病学家 R 手册内的表格中,行的顺序按升序排列,“其他”和“缺失”行位于表格中间。但我想最后得到这些行。如何做到这一点?

https://epirhandbook.com/en/tables-for-presentation.html

我希望表中的行顺序如下所示:

Central Hospital
Military Hospital
Port Hospital
St. Mark's Maternity Hospital (SMMH)
Other
Missing
Total
r dplyr flextable
2个回答
0
投票

最简单的方法是使用您需要的行的索引:

ids=which(df$Hospital %in% c('Other', 'Missing', 'Total') #哪些行应该位于数据框的底部

df2=df[ids,] # 仅使用此行创建临时数据框;

df=df[-c(ids),] #从数据框中删除它们

df=rbind(df,df2) # 将此行追加到底部。

#或者,可能更容易:

ids=which(df$Hospital %in%c('其他', '失踪', '总计')

df=rbind(df[-c(ids),],df[ids,])


0
投票
library(dplyr)
library(forcats)

df |>
  arrange(fct_relevel(Hospital, c("Other", "Missing", "Total"), after = Inf))

输出:

                              Hospital
1                     Central Hospital
2                    Military Hospital
3                        Port Hospital
4 St. Mark's Maternity Hospital (SMMH)
5                                Other
6                              Missing
7                                Total

使用数据:

> dput(df)
structure(list(Hospital = c("St. Mark's Maternity Hospital (SMMH)", 
"Central Hospital", "Other", "Military Hospital", "Missing", 
"Port Hospital", "Total")), class = "data.frame", row.names = c(NA, 
-7L))
© www.soinside.com 2019 - 2024. All rights reserved.