Reputation: 664
I'm trying to create a function that will identify duplicate samples (rows) based off of an ID number and create a new column which will write the test order of the duplicated samples (if any).
The duplicate samples will have the same ID, but will have a secondary ID that is sequential. Below is an example of what I mean.
Example data:
df <- data.frame(ID1=c(2528,2528,2528,2530,2533,2533),
ID2=c("G_54", "G_55", "G_53", "G_99", "G_252", "G_253"),
RESULT=c(.235, .237, .236, .325, .445, .446))
df
# ID1 ID2 RESULT
# 1 2528 G_54 0.235
# 2 2528 G_55 0.237
# 3 2528 G_53 0.236
# 4 2530 G_99 0.325
# 5 2533 G_252 0.445
# 6 2533 G_253 0.446
I would like the result to look like this:
#expected output
# ID1 ID2 RESULT RUN
# 2528 G_54 0.235 RUN2
# 2528 G_55 0.237 RUN3
# 2528 G_53 0.236 RUN1
# 2530 G_99 0.325 SINGLE
# 2533 G_252 0.445 RUN1
# 2533 G_253 0.446 RUN2
Upvotes: 2
Views: 76
Reputation: 56149
Using dplyr:
library(dplyr)
df %>%
group_by(ID1) %>%
arrange(ID1, ID2) %>%
mutate(RUN = row_number(),
N = n(),
RUN = ifelse(N == 1, "SINGLE", paste0("RUN", RUN))) %>%
select(-N)
#result
# ID1 ID2 RESULT RUN
# 1 2528 G_53 0.236 RUN1
# 2 2528 G_54 0.235 RUN2
# 3 2528 G_55 0.237 RUN3
# 4 2530 G_99 0.325 SINGLE
# 5 2533 G_252 0.445 RUN1
# 6 2533 G_253 0.446 RUN2
Upvotes: 2