简体   繁体   中英

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

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)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM