Claudio Moneo
Claudio Moneo

Reputation: 569

Manipulating Duplicates

I have a vector in R, with some duplicates:

v <- c(1,1,1,2,2,3)

Now I want a function that replaces the duplicates to get a sequence of increasing suffixes:

result <- c(1,1.2,1.3,2,2.2,3)

Upvotes: 1

Views: 60

Answers (3)

Duck
Duck

Reputation: 39613

Here a solution using dplyr, maybe not so easy as the previous answers of @RuiBarradas and @RonakShah because you have to transform into dataframe and make some manipulations but it can be helpful:

library(tidyverse)
v <- c(1,1,1,2,2,3)
#Dataframe
v1 <- data.frame(v)
#Mutate
v1 %>% group_by(v) %>% mutate(v2=as.character(1:n()),
                              v2=ifelse(v2=='1',as.character(v),paste0(v,'.',v2))) %>% 
  ungroup() %>% select(v2)

# A tibble: 6 x 1
  v2   
  <chr>
1 1    
2 1.2  
3 1.3  
4 2    
5 2.2  
6 3    

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76663

Here is a solution with ave. Though @Ronak Shah already posted a solution also with ave, I believe this one is different.

ave(v, v, FUN = function(x) x + c(0, seq_along(x)[-1])/10)
#[1] 1.0 1.2 1.3 2.0 2.2 3.0

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389275

Using ave, you can create a sequence number for each repeat :

ave(v, v, FUN = seq_along)
#[1] 1 2 3 1 2 1

Divide this by 10 to get

ave(v, v, FUN = seq_along)/10
#[1] 0.1 0.2 0.3 0.1 0.2 0.1

Now add v to it

v1 <- v + ave(v, v, FUN = seq_along)/10
v1
#[1] 1.1 1.2 1.3 2.1 2.2 3.1

Now, since you don't want to change the first value of each group you can do :

v1[!duplicated(v)] <- unique(v)
v1
#[1] 1.0 1.2 1.3 2.0 2.2 3.0

Upvotes: 3

Related Questions