Daniel Daniel -4 years ago 100
R Question

Differentiate ID according to another variable

I need to differentiate the column ID (with a letter) if they are different in other variable ("Art" in this case). Like this:

Id<-c("RoLu1976", "RoLu1976", "AlBlKyFy1989", "ThSa1996", "AlBlKyFy1989","ThSa1996")
Art<-c("Econometric Policy Evaluation", "Policy Right", "Rules", "Expectations", "Nonneutrality of money","Expectations")
Yr<-c(1976, 1976, 1989, 1996, 1989, 1996)

In the above the Ids should be:

Id Art Yr
RoLu1976a Econometric Policy Evaluation 1976
RoLu1976b Policy Right 1976
AlBlKyFi1989a Rules 1989
ThSa1996 Expectations 1996
AlBlKyFi1989b Nonneutrality of money 1989
ThSa1996 Expectations 1996

In this case, column ID are identical in some cases (for example with
) but different in "Art" column.

Answer Source

A data.table solution


df[, tmp := seq(uniqueN(Art)), by = Id]
df[, addition := ifelse(.N>1, "",letters[tmp]), by = .(Id, Art)]
df[, Id := paste0(Id, addition)]
df[, c("tmp", "addition") := NULL]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download