0

I have the 2 dataframes below

    name<-c("Adam","Bill","Jack")
    value<-c(3,2,1)
    n<-data.frame(name,value)
    
    name value
    1 Adam     3
    2 Bill     2
    3 Jack     1

    id<-c("Adam","Adam","Bill","Jack","Jack")
    group<-c("A","A","A","B","B")
    e<-data.frame(id,group)

    id group
    1 Adam     A
    2 Adam     A
    3 Bill     A
    4 Jack     B
    5 Jack     B

in which I want to match the values from n$name and e$id and then create a new column group in n with the respective values found in e$group like:

name value group
1 Adam     3     A
2 Bill     2     A
3 Jack     1     B

3 Answers 3

2

You can use match:

n$group <- e$group[match(n$name, e$id)]
n
#  name value group
#1 Adam     3     A
#2 Bill     2     A
#3 Jack     1     B
Sign up to request clarification or add additional context in comments.

Comments

2

Keep only unique rows of e and merge

merge(n, unique(e), by.x = 'name', by.y = 'id')

#  name value group
#1 Adam     3     A
#2 Bill     2     A
#3 Jack     1     B

With dplyr :

library(dplyr)
n %>% inner_join(distinct(e), by = c('name' = 'id'))

Comments

2

We can use data.table

library(data.table)
setDT(n)[unique(e), on = .(name = id)]
#     name value group
#1: Adam     3     A
#2: Bill     2     A
#3: Jack     1     B

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.