I have two dataframes.
One contains pairs of correct and incorrect place names:
place <- data.frame(
place_correct = c("London", "Birmingham", "Newcastle", "Brighton"),
place_incorrect = c("Lundn", "Birmgham", "Nexcassle", "Briton"), stringsAsFactors = F)
The other contains a column with a mix of these correct and incorrect place names:
set.seed(123)
df <- data.frame(town = sample(c("London", "Birmingham", "Newcastle", "Brighton",
"Lundn", "Birmgham", "Nexcassle", "Briton"), 20, replace = T), stringsAsFactors = F)
What I'd like to do is match the incorrect place names in df to the incorrect place names in place and replace them by the correct place name.
EDIT:
I can do it in base R using ifelse and %in%:
df$town_correct <- ifelse(df$town %in% place$place_incorrect,
place$place_correct[match(df$town, place$place_incorrect)],
df$town)
df
town town_correct
1 Newcastle Newcastle
2 Nexcassle Newcastle
3 Brighton Brighton
4 Briton Brighton
5 Briton Brighton
6 London London
7 Lundn London
8 Briton Brighton
9 Lundn London
10 Brighton Brighton
11 Briton Brighton
12 Brighton Brighton
13 Birmgham Birmingham
14 Lundn London
15 London London
16 Briton Brighton
17 Birmingham Birmingham
18 London London
19 Newcastle Newcastle
20 Briton Brighton
But how can it be done in dplyr?