我想按行名对几个表进行排序,行名的顺序相同,例如基于向量.

我的问题是,我不想按字母顺序排序,而是按特定的顺序排序.

此外,每个表的大小和行名都不相同,但它们的其余行名应该遵循相同的顺序.

Reproducible example

### Initiating data
# Complete table with unordered rownames
tabComplete <- data.frame(Group=c("E", "A", "D", "B", "C"),
                          Values=c("order", "This", "correct", "is", "the"), 
                          row.names=c("Fifth", "First", "Fourth", "Second", "Third"))

           Group Values
Fifth      E order
First      A This
Fourth     D correct
Second     B is
Third      C the

# Two tables that I would like to order by rownames
tabPortion1 <- tabComplete[c(1, 3, 5), ]
tabPortion2 <- tabComplete[c(1, 2, 4), ]
    
       Group  Values
Fifth      E   order
Fourth     D correct
Third      C     the
    
       Group Values
Fifth      E  order
First      A   This
Second     B     is

What I would like to achieve

# Based on a vector, I would like that every table follow the same order but the have different sizes
vecMyOrder <- c("First", "Second", "Third", "Fourth", "Fifth")

# Tables with the correct order
tabComplete[c("First", "Second", "Third", "Fourth", "Fifth"), ]
tabPortion1[c("Third", "Fourth", "Fifth"), ]
tabPortion2[c("First", "Second", "Fifth"), ]

       Group  Values
First      A    This
Second     B      is
Third      C     the
Fourth     D correct
Fifth      E   order

       Group  Values
Third      C     the
Fourth     D correct
Fifth      E   order

       Group Values
First      A   This
Second     B     is
Fifth      E  order

谢谢

推荐答案

给出一个数据帧列表lst <- list(tabComplete, tabP或tion1, tabP或tion2),您可以try 这样做

lapply(
    lst,
    \(x) x[或der(match(row.names(x), vecMyOrder)), ]
)

lapply(
    lst,
    \(x) x[或der(fact或(row.names(x), levels = vecMyOrder)), ]
)

这给了我们

[[1]]
       Group  Values
First      A    This
Second     B      is
Third      C     the
Fourth     D c或rect
Fifth      E   或der

[[2]]
       Group  Values
Third      C     the
Fourth     D c或rect
Fifth      E   或der

[[3]]
       Group Values
First      A   This
Second     B     is
Fifth      E  或der

R相关问答推荐

从具有随机模式的字符串中提取值

R等效于LABpascal(n,1)不同的列符号

Highcharter多次钻取不起作用,使用不同方法

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

我正在努力用R计算数据集中的中值逐步距离

R spatstat Minkowski Sum()返回多个边界

Select 季度月值

解析R函数中的变量时出现的问题

如何从容器函数中提取conf并添加到ggplot2中?

在R中,如何从一系列具有索引名的变量快速创建数据帧?

如何使用字符串从重复的模式中提取多个数字?

R中时间间隔的大向量与参考时间间隔的相交

用多边形替换地块点

有没有办法将基于每个值中出现的两个关键字或短语的字符串向量重新编码为具有这两个值的新向量?

如何将宽格式的患者信息数据高效地转换为患者计数的时间序列?

计算多变量的加权和

如何在shiny 的应用程序 map 视图宣传单中可视化单点

从两个数据帧中,有没有办法计算R中一列的唯一值?

列间序列生成器的功能

R中的交叉表