How to assign a unique identifier to multiple records in a data frame

I have a large data frame that has three identifiers. For instance:

df <- data.frame(year=c(1999,1999,2000,2000,2000), country=c('K','K','M','M','S'), 
                 site=c('di','se','di','di','di'))

What will create such a data frame:

    year country site
    1999    K     di
    1999    K     se
    2000    M     di
    2000    M     di
    2000    S     di

I want to add an extra column to the data frame and assign a "unique identifier" using the entries for "year", "country" and "site". It will look something like this:

    year country site unique_id
    1999    K     di     1
    1999    K     se     2
    2000    M     di     3
    2000    M     di     3
    2000    S     di     4

Any suggestions on how to do this would be greatly appreciated. I think this could be done with the plyr package ?

+5
source share
2 answers

. ( , as.numeric() / ).

df$unique_id <- 
    as.numeric(as.factor(with(df, paste(year, country, site, sep="_"))))
df
#   year country site unique_id
# 1 1999       K   di         1
# 2 1999       K   se         2
# 3 2000       M   di         3
# 4 2000       M   di         3
# 5 2000       S   di         4
+7

:

lookup <- data.frame(id=1:length(unique(apply(df, 1, paste, collapse=""))), key=unique(apply(df, 1, paste, collapse="")))

df$id <- apply(df, 1, function(x) lookup[lookup$key==paste(x, collapse=""), "id"])
+1

All Articles