mercredi 5 mai 2021

Find a string from Column A in Column B without grepl

I have three columns:

> df
  ID     city destination
1  1   London           3
2  2    Paris           2
3  3 New York           5
4  4    Tokyo           4
5  5  Beijing           1

I need to add a 4th column that takes whatever the value is in the Destination column, finds it in the ID column, then pulls out the associated string in the City column - so that it would look like this

  ID     city destination city_destination
1  1   London           3         New York
2  2    Paris           2            Paris
3  3 New York           5          Beijing
4  4    Tokyo           4            Tokyo
5  5  Beijing           1           London

I know how to look up a value in the ID column and return something:

df_destination <- df %>%
  mutate(city_destination = ifelse(grepl("3", ID), 1, 0))

But I cannot figure out how to

  1. Go through each value in Column A and look for it in Column B
  2. Return a string from Column C

Help on this would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire