簡體   English   中英

根據另一個數據幀中的匹配條件將列添加到 R 中的數據幀

[英]Adding column to a dataframe in R based on matching conditions in another dataframe

我有 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

嘗試這個:

DF3 <- merge(DF1,DF2, by.x = c("Batch","Patch1"), by.y=c("Batch","Patch"), all.x=TRUE) %>%
      rename(Pop_size1=Pop_size)
DF3 <- merge(DF3,DF2, by.x = c("Batch","Patch2"), by.y=c("Batch","Patch"), all.x=TRUE) %>%
      rename(Pop_size2=Pop_size)

我們可以使用data.table方法,這會更快更有效

library(data.table)
setDT(DF1)[DF2, Patch1_Pop_size := Pop_size,
  on = .(Batch, Patch1 = Patch)][DF2, 
   Patch2_Pop_size := Pop_size, on = .(Batch, Patch2 = Patch)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM