r - 比较两列以匹配值并并排对齐

标签 r sorting dataframe datatable

我拥有的数据有两列,其值应该匹配。因为,有太多行,我必须执行以下操作:

  • 加载两列
  • 比较 AB 以查找匹配值
  • AB 列的输出堆叠到两个新列中,以便匹配的值并排放置,不匹配的值位于每个列的末尾专栏。

是否有更快的方法来执行此操作,以便它适用于任何类型的数据(整数、浮点或字符)比较?

输入数据表

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/

相关文章:

使用 dc.js 对条形图中的条形进行排序

python - 使用 pandas 解析大量日期 - 可扩展性 - 性能下降速度快于线性

r - 选择具有多个不同值的组

r - 在某些值的连续运行中创建计数器

python - 根据Python中defaultdict的特定列的值对csv列进行排序

python - 数据框:创建新的数据框,在多列的基础上保持重复超过 2 次(时间限制)

python - 通过基于 "_"拆分文本来替换 Pandas 列

r - 计算未出现较早且未出现在最后一组中的新值

r - 如何将嵌套列表转换为 R 中的数据框?

python - 如何用(python)列表中的顺序替换数字