How to get duplicate IDs numbered?
3
0
Entering edit mode
b.nota ▴ 360
@bnota-7379
Last seen 3.6 years ago
Netherlands

Hello,

It might be a silly question, but I am struggling with it all day now. Hopefully someone with bright insight may be of any help.

I have this df which contains a column with ID names. Some ID names occur one time, other two, and some even 20 times. In other words some IDs are in 1 row, others in many rows.

What I would like to make is a new column which numbers the replicate IDs (from 1, 2, 3, etc.). I have tried ddply from plyr package, but that only gives me a new df with each unique ID followed by the number of replicates (that's not what I am looking for).

Any suggestions are welcome, thanks in advance!

Ben

plyr • 3.7k views
ADD COMMENT
0
Entering edit mode

It's probably not difficult to do, but it's not clear what you are after. As far as I can tell you already have the column you want. So perhaps you could give a small example?

ADD REPLY
1
Entering edit mode
@steve-lianoglou-2771
Last seen 14 months ago
United States

With plyr you probably want to do something like:

library(plyr)
newdf <- ddply(df, .(ID), function(x) {
  transform(x, replicate=1:nrow(x))
})

plyr is sooo 2010, though ;-) Here are some alternatives:

Using dplyr

library(dplyr)
newdf <- df %>%
  group_by(ID) %>%
  mutate(replicate=seq(n()))

Using data.table:

library(data.table)
dt <- as.data.table(df)
dt[, replicate := 1:.N, by="ID"]

 

 

ADD COMMENT
0
Entering edit mode
Charles Berry ▴ 290
@charles-berry-5754
Last seen 5.1 years ago
United States

ave() will give the sequential numbers, so something like

with(mydf, paste0(ID, ave( ID, ID, FUN=seq_along )))

should do it.

 

ADD COMMENT
0
Entering edit mode
b.nota ▴ 360
@bnota-7379
Last seen 3.6 years ago
Netherlands

Thanks for all the suggestions! Steve's first suggestion with 'old fashion' ;P plyr was exactly what I needed. A new column with sequential numbering of each replicate IDs. Many thanks!

ADD COMMENT

Login before adding your answer.

Traffic: 728 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6