Home > Mobile >  str_replace_all using multiple conditions
str_replace_all using multiple conditions

Time:09-16

I have two data frames ("before", "after").

before1 <- c("A", "B", "C")
before2 <- c("1", "2", "3")
before3 <- c("ab", "cd", "ef")
before <- data.frame(before1, before2, before3)

after1 <- c("A", "B")
after2 <- c("1", "2")
after3 <- c("de", "fg")
after <- data.frame(after1, after2, after3)

I want to replace before3 with after3 when before1 and before2 match both after1 and after3.

The result I want is below.

before1 <-  c("A", "B" "C")
before2 <- c("1", "2", "3")
newafter <- c("de", "fg", "ef")

CodePudding user response:

You may join the two dataframes and update with coalesce.

library(dplyr)

before %>%
  left_join(after,  by = c('before1' = 'after1', 'before2' = 'after2')) %>%
  mutate(newafter = coalesce(after3, before3)) %>%
  select(before1, before2, newafter)

#  before1 before2 newafter
#1       A       1       de
#2       B       2       fg
#3       C       3       ef
  • Related