我拥有的数据有两列,其值应该匹配。因为,有太多行,我必须执行以下操作:
- 加载两列
- 比较
A
和B
以查找匹配值 - 将
A
和B
列的输出堆叠到两个新列中,以便匹配的值并排放置,不匹配的值位于每个列的末尾专栏。
是否有更快的方法来执行此操作,以便它适用于任何类型的数据(整数、浮点或字符)比较?
输入数据表
A B
1 1
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
10 11
输出数据表
C D
1 1
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
2 11
最佳答案
这是一种方法。我可能把这个搞得太复杂了
#copy the object to another dataframe
df1 <- df
#Get matched indices for both the columns
inds1 <- match(df$A, df$B)
inds2 <- match(df$B, df$A)
#Replace value in B column in the same order as A
df1$B <- df$B[inds1]
#Order by column B
df1 <- df1[order(df1$B), ]
#Replace NA in B with unmatched value.
df1$B[is.na(df1$B)] <- df$B[is.na(inds2)]
df1
# A B
#1 1 1
#3 3 3
#4 4 4
#5 5 5
#6 6 6
#7 7 7
#8 8 8
#9 9 9
#10 10 10
#2 2 11
关于r - 比较两列以匹配值并并排对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57881775/