比较不同数据帧的更快列

时间:2022-06-01 18:59:56

Let's assume two dataframes: A and B containing data like the following one:

我们假设有两个数据帧:A和B包含如下数据:

Dataframe: A              Dataframe: B
   ColA                     ColB1      ColB2
| Dog   |                 | Lion     | yes
| Lion  |                 | Cat      | 
| Zebra |                 | Elephant | 
| Bat   |                 | Dog      | yes

Want to compare the values of ColA to the values of ColB1, in order to insert yes in case of match in column ColB2. What I'm running is this:

想要将ColA的值与ColB1的值进行比较,以便在ColB2列中匹配时插入yes。我正在运行的是这样的:

for (i in 1:nrow(B)){
    for (j in 1:nrow(A)){
         if (B[i,1] == A[j,1]){
             B[i,2] <- "yes"
         }  
    }   
}

In reality we re talking abaout 20000 lines. How could this become faster?

实际上我们正在谈论超过20000行。怎么会变得更快?

1 个解决方案

#1


2  

You can use the %in% operator to determine membership:

您可以使用%in%运算符来确定成员资格:

B$ColB2 <- B$ColB1 %in% A$ColA

ColB2 will contain TRUE/FALSE dependent on whether value in ColB1 of data frame B was found in ColA of data frame A.

ColB2将包含TRUE / FALSE,具体取决于数据帧B的ColB1中的值是否在数据帧A的ColA中找到。

For more info see:

有关详情,请参阅:

https://stat.ethz.ch/R-manual/R-devel/library/base/html/match.html

#1


2  

You can use the %in% operator to determine membership:

您可以使用%in%运算符来确定成员资格:

B$ColB2 <- B$ColB1 %in% A$ColA

ColB2 will contain TRUE/FALSE dependent on whether value in ColB1 of data frame B was found in ColA of data frame A.

ColB2将包含TRUE / FALSE,具体取决于数据帧B的ColB1中的值是否在数据帧A的ColA中找到。

For more info see:

有关详情,请参阅:

https://stat.ethz.ch/R-manual/R-devel/library/base/html/match.html