首页 > 解决方案 > Adding a True or False column for a dataframe if it matches a column of a different dataframe in R?

问题描述

I am seeing a few answers for this with Pandas in Python, but haven't found something in R. I am looking to add a 1 or 0 OR True or False boolean type column to a dataframe if that dataframe's column has matching values with another dataframe's column.

As an example, say I have a dataframe 'awesome':

Name Value
A 1
B 23
C 1
D 15
E 18
F 19

And another dataframe 'neat'

Name Sports
A Soccer
B Bball
G Ball
N Ball
Z Volley
F Boxing

I'd like to add a True or False column to the 'awesome' dataframe if the Name column in 'awesome' has a match with the 'neat' name column.

So the 'awesome' column would be: | Name | Value | has_match | | -------- | ------|------------| | A | 1 | True | | B | 23 | True | | C | 1 | False | | D | 15 | False | | E | 18 | False | | F | 19 | True |

Can someone tell me how I could do this in R?

Note: GitHub markdown table doesn't seem to be working for some reason, if anyone knows how to fix it into tables let me know... but have created a pic for easier reference:

image for reference of dataframes

标签: rdataframe

解决方案


您可以使用%in%

awesome_df$has_match <- awesome_df$Name %in% unique(neat_df$Name)

推荐阅读