ThePooh ThePooh - 9 days ago 4
R Question

Create factor based on matching rows from dataframes of unequal size

I have two dataframes

DF1
10
11
12
13
15
16
17
19


and

DF2
12
16
19


I am looking for a way to get an output as

DF3
10 0
11 0
12 1
13 0
15 0
16 1
17 0
19 1


I know how to find matched rows from two data frames

match = which(DF1 %in% DF2)


but lost in find the way to assign 0/1 for matched rows in these two dataframes. Any help is highly appreciated.

Answer

We can do this with %in% to create a logical vector, which can be coerced to binary with as.integer

DF3 <- DF1
DF3$newCol <- as.integer(DF3[,1] %in% DF2[,1])
DF3$newCol
#[1] 0 0 1 0 0 1 0 1

If we need consecutive numbers from the above result

DF3$newCol[DF3$newCol!=0] <- seq_along(DF3$newCol[DF3$newCol!=0])
DF3$newCol
#[1] 0 0 1 0 0 2 0 3
Comments