r - 根据另一个数据帧中的匹配条件将列添加到 R 中的数据帧

标签 r dataframe merge

我有 2 个数据框,我想向其中添加一列,并根据匹配条件添加另一个数据框中的值。然后我想对许多大型数据集重复此操作。

# Example dataframe

DF1 <- data.frame(Batch = c('a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b'),
           Patch1 = c(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3),
           Patch2 = c(2, 3, 1, 3, 1, 2, 2, 3, 1, 3, 1, 2))

DF2 <- data.frame(Batch = c('a', 'a', 'a', 'b', 'b', 'b'),
                             Patch = c(1, 2, 3, 1, 2, 3),
                             Pop_size = sample(1:300, size=6, replace=TRUE)) 

对于 DF1,我想添加 2 列(Patch1_popsize 和 Patch2_popsize),其中 Pop_size 在 DF2 中给出,以及给定批处理的相应补丁号

最佳答案

尝试以这种方式使用match():

#Code
DF1$Patch1_Pop_size <- DF2[match(paste(DF1$Batch,DF1$Patch1),paste(DF2$Batch,DF2$Patch)),"Pop_size"]
DF1$Patch2_Pop_size <- DF2[match(paste(DF1$Batch,DF1$Patch2),paste(DF2$Batch,DF2$Patch)),"Pop_size"]

输出:

DF1
   Batch Patch1 Patch2 Patch1_Pop_size Patch2_Pop_size
1      a      1      2             137             254
2      a      1      3             137             211
3      a      2      1             254             137
4      a      2      3             254             211
5      a      3      1             211             137
6      a      3      2             211             254
7      b      1      2              78              81
8      b      1      3              78              43
9      b      2      1              81              78
10     b      2      3              81              43
11     b      3      1              43              78
12     b      3      2              43              81

关于r - 根据另一个数据帧中的匹配条件将列添加到 R 中的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64992027/

相关文章:

python - 从 DataFrame.apply 中检索未知的列名

python - ivot_table() 到 df 没有要聚合的数字类型

python - 如何匹配某个人在不同时间段内的调查响应以形成面板数据集?

r - 将数据帧组合在两个不同的列表中,这些列表以 R 中的元素名称为键

r - ggplot 颜色 : changing order of colours, 的最佳可视化保持原始因子排序

r - 用户从 R 查找 Twitter API 会导致错误 (403)

python - 按条件选择行

python - 在 Python (pandas) 的多列中进行 Vlookup

使用 ggplot 对facet_wrap 的级别重新排序

r - 无法将 "e"输入我的指数衰减函数