首页 > 解决方案 > How to do a lookup or match from 1 dataframe to another?

问题描述

I have two data frames I am working with.

data 1


> data1
    ID
1  123
2  124
3  125
4  128
5  135
6  160
7  185
8  195
9  201
10 101
11 584

data 2

> data2
   ID
1 123
2 124
3 125
4 128
5 160
6 195
7 201

My desired output is have a new column that identifies if an ID from data1 is on data2.

Here is my desired output as a table.

    ID On.data2.
1  123       Yes
2  124       Yes
3  125       Yes
4  128       Yes
5  135        No
6  160       Yes
7  185        No
8  195       Yes
9  201       Yes
10 101        No
11 584        No

data

data1 <- data.frame(ID = c(123,124,125,128,135,160,185,195,201,101,584))
data2 <- data.frame(ID = c(123,124,125,128,160,195,201))

标签: rdplyrtidyverse

解决方案


A simple if_else statement is enough:

data1$On.data2 = ifelse(data1$ID %in% data2$ID, "yes", "no")
   ID On.data2
1  123      yes
2  124      yes
3  125      yes
4  128      yes
5  135       no
6  160      yes
7  185       no
8  195      yes
9  201      yes
10 101       no
11 584       no

推荐阅读