adam.888
adam.888

Reputation: 7846

R replace an id value with a name

I have a dataframe which holds an id and a result:

df <- data.frame(id=c(1,4,3,3,2,1),result=c(90,75,45,56,78,66))
df

I also have a key which holds a name for each id:

key <- data.frame(id=c(1:4),name=c("Jon","Fred","Jane","Jim"))
key 

How can I replace an id value in df with a name value from the key?

Thank you for your help.

Upvotes: 3

Views: 8293

Answers (5)

TheLogan
TheLogan

Reputation: 31

Also you could use join functions:

df1 <- df %>%
  full_join(key, by = 'id') %>%
  select(-id)

Upvotes: 2

agstudy
agstudy

Reputation: 121578

 df$id <- ave(df,df$id,
        FUN = function(x)  as.character(key$name[key$id==unique(x$id)]))[1]

df
    id result
1  Jon     90
2  Jim     75
3 Jane     45
4 Jane     56
5 Fred     78
6  Jon     66

Upvotes: 2

IRTFM
IRTFM

Reputation: 263352

> df[["id"]] <- key[ match(df[['id']], key[['id']] ) , 'name']
> df
    id result
1  Jon     90
2  Jim     75
3 Jane     45
4 Jane     56
5 Fred     78
6  Jon     66

Upvotes: 4

mavam
mavam

Reputation: 12552

You can simply use merge:

merge(df, key)[-1]

(The -1 removes the ID column in the merged data frame.)

Upvotes: 6

user1317221_G
user1317221_G

Reputation: 15441

you could

merge(df,key,by="id" ,all = TRUE)

then remove or change names of columns as you wish.

Upvotes: 2

Related Questions