user8990745
user8990745

Reputation:

how can I assign a name to duplicate

my data is like this

df<- structure(list(label = c("afghanestan", "afghanestan", "afghanestanIndia", 
"afghanestanindiaholad", "afghanestanUSA", "USA", "Argentina", 
"Brazil", "Argentinabrazil", "Brazil"), Start = c(114, 516, 89, 
22, 33, 67, 288, 362, 45, 362), Stop = c(127, 544, 105, 34, 50, 
85, 299, 381, 68, 381)), class = "data.frame", .Names = c("label", 
"Start", "Stop"), row.names = c(NA, -10L))

when I want to remove the exact duplicate , I simply do this

df[!duplicated(df[,c('label','Start','Stop')]),]

now the problem is that I want to recognize those that are similar in the label but possibly different in the start and stop. so I would like to generate something like this afterwards

                  label Start Stop NewLab
1           afghanestan   114  127  TRUE
2           afghanestan   516  544  TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FLASE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE

Upvotes: 0

Views: 43

Answers (2)

Stuart Allen
Stuart Allen

Reputation: 1592

This would work in a single line of code:

df$NewLab <- df$label %in% df[duplicated(df$label), ]$label

And the output:

> df$NewLab <- df$label %in% df[duplicated(df$label), ]$label
> df
                  label Start Stop NewLab
1           afghanestan   114  127   TRUE
2           afghanestan   516  544   TRUE
3      afghanestanIndia    89  105  FALSE
4 afghanestanindiaholad    22   34  FALSE
5        afghanestanUSA    33   50  FALSE
6                   USA    67   85  FALSE
7             Argentina   288  299  FALSE
8                Brazil   362  381  FALSE
9       Argentinabrazil    45   68  FALSE

Or in dplyr notation:

df <- dplyr::mutate(df, NewLab = label %in% df[duplicated(df$label), ]$label)

Upvotes: 1

B Williams
B Williams

Reputation: 2050

Here is a somewhat convoluted methods using dplyr

library(tidyverse) 

df %>% 
  group_by(label) %>% 
  mutate(n = n()) %>% 
  group_by(Start, Stop) %>% 
  mutate(n2 = n()) %>% 
  mutate(newlabel = ifelse(n>1 & n2==1, TRUE, FALSE)) %>%
  dplyr::select(-n, -n2)

First create a grouping variable of labels - take a count, then a grouping variable of start and stop times - take a count, use an ifelse to assign True/False, then remove the intermediate columns.

Upvotes: 0

Related Questions