根据值是否存在于R中的其他数据框中,将新值添加到新列中 [英] Add new value to new column based on if value exists in other dataframe in R

查看:44
本文介绍了根据值是否存在于R中的其他数据框中,将新值添加到新列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个分别称为 users purchases 的数据框,每个数据框都有成千上万个数据集.两者都具有称为 ID 的功能.

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

我的目的是,如果 purchases 存在于个用户 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆