使用健全性检查基于字符类型列对多个数据表进行排序 [英] Sorting Multiple Data Tables Based On Character Type Column With Sanity Check

查看:109
本文介绍了使用健全性检查基于字符类型列对多个数据表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据表,并希望对它们进行排序,以使第一个表的行值与第二个表的行值基于名为Parameter的列相同.

I have two data table and want to sort them such that row value of first table is same as row value of second table based on a column named Parameter.

使用order(),问题在于它只会根据输入的数据表进行排序.但是要确保不仅两个数据表都基于Parameter列进行排序,而且还可以通过比较两个数据表之间的Parameter列逐行进行正确性排序来进行正确排序.

Using order(), the problem is that it will only sort based on the data table input. But to ensure that not only both data tables are sorted based on Parameter column, but are also sorted correctly by comparing the column Parameter row by row between two data tables as a sanity check.

请分享任何更快速的方法.

Please share any faster way to do this.

第一表输入

Parameter   Data
R-1          1
R-2          1
R-3          1
P-11         1
P-12         1
P-8          2
P-9          1
P-10         1
R-4          1
R-5          1
P-14         1
P-15         1

第二表输入

Parameter   Data
R-1          2
P-9          2
R-3          2
P-11         2
P-12         2
P-8          2
R-2          2
P-10         2
R-4          2
R-5          3
P-14         2
P-15         2

所需的输出

第一张表的输出

Parameter   Data
R-1         1
R-2         1
R-3         1
R-4         1
R-5         1
P-8         2
P-9         1
P-10        1
P-11        1
P-12        1
P-14        1
P-15        1

第二表输出

Parameter   Data
R-1         2
R-2         2
R-3         2
R-4         2
R-5         3
P-8         2
P-9         2
P-10        2
P-11        2
P-12        2
P-14        2
P-15        2

推荐答案

这是使用dplyrtidyr::separate的方法.

library(dplyr); library(tidyr)

# Function to split up parameter into two pieces and sort like example
sort_table <- function(df) {
  df %>%  separate(Parameter, c("letter", "num"), remove = F) %>%
  arrange(desc(letter), as.numeric(num))
}

# Join the two sorted tables
full_join(
  sort_table(table_1),
  sort_table(table_2),
  by = c("Parameter", "letter", "num")
)



#   Parameter letter num Data.x Data.y
#1        R-1      R   1      1      2
#2        R-2      R   2      1      2
#3        R-3      R   3      1      2
#4        R-4      R   4      1      2
#5        R-5      R   5      1      3
#6        P-8      P   8      2      2
#7        P-9      P   9      1      2
#8       P-10      P  10      1      2
#9       P-11      P  11      1      2
#10      P-12      P  12      1      2
#11      P-14      P  14      1      2
#12      P-15      P  15      1      2

这篇关于使用健全性检查基于字符类型列对多个数据表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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