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

主宰稳场 提交于 2021-02-13 05:38:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!