根据值是否存在于 R 中的其他数据框中,将新值添加到新列 [英] Add new value to new column based on if value exists in other dataframe in R
本文介绍了根据值是否存在于 R 中的其他数据框中,将新值添加到新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个名为 users 和 purchases 的数据框,每个都有数千个数据集.两者都有一个名为 ID 的功能.
I have two dataframes called users and purchases with thousands of datasets to each. Both have a feature called ID.
我的目标是添加一个名为 buyer 的新列到数据框 purchases,如果 purchasesID 的值/em>存在于用户的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))
它应该看起来像:
推荐答案
我们可以使用 %in%
来比较值并包装 as.integer
来转换逻辑值为整数.
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
这也可以写成:
purchases$buyers <- +(purchases$ID %in% users$ID)
这篇关于根据值是否存在于 R 中的其他数据框中,将新值添加到新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文