LDT
LDT

Reputation: 3088

Assign an ID in one column based on the ID in another column in R

I have first assigned a unique id based on column 1

column1   id.1 column2 
   A      1      C
   A      1      B
   B      2      B
   C      3      A
   C      3      D

and I would like to allocate the id.1 values to column2

column1   id.1 column2  id.2
   A      1      C        3
   A      1      B        2
   B      2      B        2
   C      3      A        1
   C      3      D        NA

I am sorry if this has been answered again. I am trying for long to find a beautiful solution on that. Thank you for your time

Upvotes: 0

Views: 259

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145835

match is the usual way to do this:

df$id.2 = df$id.1[match(df$column2, df$column1)]
df
#   column1 id.1 column2 id.2
# 1       A    1       C    3
# 2       A    1       B    2
# 3       B    2       B    2
# 4       C    3       A    1
# 5       C    3       D   NA

Or using dplyr syntax:

mutate(df, id.2 = id.1[match(column2, column1)])

Using this data:

df = read.table(text = 'column1   id.1 column2 
    A      1      C
    A      1      B
    B      2      B
    C      3      A
    C      3      D', header = T)

Upvotes: 1

Onyambu
Onyambu

Reputation: 79258

you could use factor as shown below:

 transform(df, id.2 = factor(column2, unique(column1), unique(id.1)))
  column1 id.1 column2 id.2
1       A    1       C    3
2       A    1       B    2
3       B    2       B    2
4       C    3       A    1
5       C    3       D <NA>

Upvotes: 0

Related Questions