Home > Enterprise >  Compare two columns, find the common data, and get the value from the first column in R
Compare two columns, find the common data, and get the value from the first column in R

Time:07-16

I am new in R and I am trying to solve something.

I have three columns Employee, Location and Manager. I need to find if the manager for each employee is local or not, meaning that they have the same location (based on the employee column, as every manager is also an employee). For example, Manager 24 checks on locations A and B, but is a local manager only for employee 12, but not for employee 54. I want to add a new column named localManager and return "yes" or "no".

I hope that is clear. Thank you for the help!

Employee Location Manager
12 A 24
54 B 24
24 A 52
30 C 63

CodePudding user response:

The easiest way I can think to solve this is by creating a second table of the manager locations alone, then joining that table to the original one so we have a new column for "manager's location" as well as "employee location". Then creating your new boolean column is as simple as checking if manager location is equal to employee location:

dat <- dplyr::tribble(
  ~employee, ~location, ~manager,
  12, "A", 24,
  54, "B", 24,
  24, "A", 52,
  30, "C", 63
)

# Create a new table of managers only
mgr_dat <- dat[dat$employee%in           
  •  Tags:  
  • r
  • Related