Minfetli
Minfetli

Reputation: 299

Add new value to new column based on if value exists in other dataframe in R

I have two dataframes called users and purchases with thousands of datasets to each. Both have a feature called ID.

My aim is to add a new column called buyer to the dataframe purchases, if the value of ID of purchases exists in ID of users.

So the two dataframes look like this:

users = data.frame("ID" = c(23432,75645,5465645,5656,6456))
purchases = data.frame("ID" = c(6456,4436,88945))

It should look like: Desired outcome

Upvotes: 3

Views: 2077

Answers (2)

akrun
akrun

Reputation: 886948

We can use ifelse

purchases$buyersr <- ifelse(purchases$ID %in% users$ID, 1, 0)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388817

We can use %in% to compare the values and wrap as.integer to convert logical values to integers.

purchases$buyers <- as.integer(purchases$ID %in% users$ID)
purchases

#     ID buyers
#1  6456      1
#2  4436      0
#3 88945      0

This can also be written as :

purchases$buyers <- +(purchases$ID %in% users$ID)

Upvotes: 1

Related Questions