Question: How to get duplicate IDs numbered?
0
gravatar for b.nota
3.6 years ago by
b.nota320
Netherlands
b.nota320 wrote:

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 • 1.5k views
ADD COMMENTlink modified 3.6 years ago • written 3.6 years ago by b.nota320

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 REPLYlink written 3.6 years ago by James W. MacDonald49k
Answer: How to get duplicate IDs numbered?
1
gravatar for Steve Lianoglou
3.6 years ago by
Denali
Steve Lianoglou12k wrote:

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 COMMENTlink written 3.6 years ago by Steve Lianoglou12k
Answer: How to get duplicate IDs numbered?
0
gravatar for Charles Berry
3.6 years ago by
Charles Berry290
United States
Charles Berry290 wrote:

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

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

should do it.

 

ADD COMMENTlink modified 3.6 years ago • written 3.6 years ago by Charles Berry290
Answer: How to get duplicate IDs numbered?
0
gravatar for b.nota
3.6 years ago by
b.nota320
Netherlands
b.nota320 wrote:

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 COMMENTlink written 3.6 years ago by b.nota320
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 16.09
Traffic: 339 users visited in the last hour