1

I just read through comparable questions, but found no answering my specific problem. I have two dataframes,

df1 <- data.frame("name" = c("11-24", "Tim", "Anna", "67-14", "A0839", "A4b", "Lisa", "Selina"))
df2 <- data.frame("abbreviation" = c("11-24", "67-14", "A0839", "A4b"),
                  "name" = c("Charles", "Nick", "Harry", "Lola"))

Looking like this:

> df1
    name
1  11-24
2    Tim
3   Anna
4  67-14
5  A0839
6    A4b
7   Lisa
8 Selina

> df2
  abbreviation    name
1        11-24 Charles
2        67-14    Nick
3        A0839   Harry
4          A4b    Lola

I want to replace the abbreviations found in the column "name" of df1 by the matching name in df2. So that 11-24 is replaced by Charles or A4b by Lola.

What I tried was:

df1 <- df1 %>% 
       mutate(name = ifelse(name %in% df2$abbreviation, df2$name, name))

But this give not the result I want. I want:

> df1
        name
    1Charles
    2    Tim
    3   Anna
    4   Nick
    5  Harry
    6   Lola
    7   Lisa
    8 Selina

My dataframes have a different length. I am looking for a tidyverse-solution, maybe one of you has something in mind..

This would help me a lot :) Best, Kathrin

3 Answers 3

2

Using join and coalesce.

library(dplyr)

df1 %>%
  left_join(df2, by = c('name' = 'abbreviation')) %>%
  transmute(name = coalesce(name.y, name))

#     name
#1 Charles
#2     Tim
#3    Anna
#4    Nick
#5   Harry
#6    Lola
#7    Lisa
#8  Selina
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you! I don't know why but I thought that left_join will not.. This helped me :)
1

Base R solution:

idx <- match(df1$name, df2$abbreviation)
transform(df1, name = ifelse(!is.na(idx), df2$name[idx], name))

Comments

1

In base you can use match to make this update join.

idx <- match(df1$name, df2$abbreviation)
idxn <- which(!is.na(idx))
#idxn <- !is.na(idx) #Alternative
df1$name[idxn] <- df2$name[idx[idxn]]
df1
#     name
#1 Charles
#2     Tim
#3    Anna
#4    Nick
#5   Harry
#6    Lola
#7    Lisa
#8  Selina

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.