当列1与不同向量中的值匹配时,从第3列返回值

C. *_*ney 0 r

我有一个a带有多个ID代码的向量:

a <- c(167.1, 89.7, 284.1, 108.1, 50.6, 276.5, 283.2, 357.3, 119.2, 92.2, 314.4, 400.2, 154.5, 104.5, 198.2)
> a
[1] 167.1  89.7 284.1 108.1  50.6 276.5 283.2 357.3 119.2  92.2 314.4 400.2 154.5 104.5 198.2
Run Code Online (Sandbox Code Playgroud)

我还有y三列数据框:一个是ID代码,下一个是物种名称,第三个是生物变量(请注意,在我的完整数据集中,有许多行具有相同的Drop_ID值):

> y[4:14,]
Drop_ID           Common.Name distance_m
4    170.4 Greenspotted Rockfish      0.389
5    167.1             Bocaccio       0.390
6    163.1 Greenspotted Rockfish      0.393
7    193.1       Copper Rockfish      0.404
8    108.1   Shortbelly Rockfish      0.405
9    114.2       Spotted Ratfish      0.405
10   190.1          Chilipepper       0.411
11   198.2          Chilipepper       0.413
12   170.4 Greenspotted Rockfish      0.423
13   119.2   Shortbelly Rockfish      0.424
14   159.2        Widow Rockfish      0.431
Run Code Online (Sandbox Code Playgroud)

在一个新的向量中,我想在值与值y$Drop_ID匹配时报告y 中的值,a以便最终结果应如下所示:

>b
Drop_ID           Common.Name distance_m
1   167.1             Bocaccio       0.390
2   108.1   Shortbelly Rockfish      0.405
3   198.2          Chilipepper       0.413
4   119.2   Shortbelly Rockfish      0.424
Run Code Online (Sandbox Code Playgroud)

到目前为止,我唯一想到的就是使用嵌套if语句检查每一行的for循环,如果匹配发生,存储值,但我确信必须有更好的方法来执行此操作.

谢谢.

jer*_*ycg 6

您可以将其子集化:

y[y$Drop_ID %in% a, ]
Run Code Online (Sandbox Code Playgroud)