重新排序对称标题 [英] Re-ordering a symmetric tibble

查看:33
本文介绍了重新排序对称标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我们有一个 tibble,如下所示.理论上,第一列只是一个 rownames,它必须与列的名称一一对应.

Imagine we have a tibble like shown below. In theory, the first column acts simply a rownames that must have one-on-one correspondence with the columns' names.

例如,排除第一列(row_name),左起第三列名为G,但对应的行为E.

For example, excluding the first column (row_name), the third column from the left is named G, but the the corresponding row is E.

我想知道我们如何重新排列行(例如,将标题为 G 的行向上两行)以使行和列匹配?

I was wondering how we could re-order the rows (e.g., bring up row titled G two rows up) so the rows and columns match?

out <- tibble(row_name=factor(c("A","B","E","F","G")),`A`=as.character(1:5),`B`=as.character(c(2,NA,0:2)),
`G`=as.character(4:8),`E`=as.character(4:8),`F`=as.character(4:8))


#  row_name A     B     G     E     F    
#  <fct>    <chr> <chr> <chr> <chr> <chr>
#1 A        1     2     4     4     4    
#2 B        2     NA    5     5     5    
#3 E        3     0     6     6     6    
#4 F        4     1     7     7     7    
#5 G        5     2     8     8     8


# EXPECTED OUTPUT:

#  row_name A     B     G     E     F    
#  <fct>    <chr> <chr> <chr> <chr> <chr>
#1 A        1     2     4     4     4    
#2 B        2     NA    5     5     5
#5 G        5     2     8     8     8
#3 E        3     0     6     6     6    
#4 F        4     1     7     7     7   

推荐答案

如果我们想重新排列行,在 slice

If we want to reorder the rows, use match within slice

library(dplyr)
out %>%
   slice(match(names(.)[-1], row_name))

-输出

# A tibble: 5 x 6
  row_name A     B     G     E     F    
  <fct>    <chr> <chr> <chr> <chr> <chr>
1 A        1     2     4     4     4    
2 B        2     <NA>  5     5     5    
3 G        5     2     8     8     8    
4 E        3     0     6     6     6    
5 F        4     1     7     7     7  


或者在arrange

out %>% 
    arrange(factor(row_name, levels = names(.)[-1]))

-输出

# A tibble: 5 x 6
  row_name A     B     G     E     F    
  <fct>    <chr> <chr> <chr> <chr> <chr>
1 A        1     2     4     4     4    
2 B        2     <NA>  5     5     5    
3 G        5     2     8     8     8    
4 E        3     0     6     6     6    
5 F        4     1     7     7     7   

这篇关于重新排序对称标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆