问题
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:
回答1:
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)
回答2:
We can use ifelse
purchases$buyersr <- ifelse(purchases$ID %in% users$ID, 1, 0)
来源:https://stackoverflow.com/questions/61456498/add-new-value-to-new-column-based-on-if-value-exists-in-other-dataframe-in-r