Reputation: 7
I am relatively new to R. I need some help with more of a find and replace function but it is a bit more selective.
The example datasets I am using can be derived through:
name_1 <- c("Madeline","Maximillian","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)
name_2 <- c("Madeline","Maximillian","Maxon","Mad")
nickname_1 <- c("Mad","Max","M","N/A")
nickname_2 <- c("Madine","Maxim","N/A","N/A")
nickname_table <- data.frame(name_2,nickname_1,nickname_2)
I want to replace the name of the scoreboard table with the second nickname. In that case, it would result in scoreboard_table to turn into:
name_1 <- c("Madine","Maxim","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)
I am sure if doing a for loop would be easier or making an if, else statement. How should I go about this overall?
Thank you for the help in advance. It is really appreciated.
Upvotes: 0
Views: 43
Reputation: 389115
You can perform a join and use coalesce
to get names from nickname_2
.
library(dplyr)
left_join(scoreboard_table, nickname_table, by = c('name_1' = 'name_2')) %>%
transmute(name_1 = coalesce(nickname_2, name_1),
value) -> scoreboard_table
scoreboard_table
# name_1 value
#1 Madine 2.3
#2 Maxim 3.4
#3 Maxon 7.5
#4 Mad 1.9
#5 Marvin 16.2
If they are not already change the "N/A"
values to real NA
in your data.
nickname_table[nickname_table == 'N/A'] <- NA
Upvotes: 1