Home > Software design >  Append occurrence number to each element
Append occurrence number to each element

Time:11-09

Maybe the problem does not match the topic, and it is a bit difficult to describe the problem. I have a matrix like the following:

  V1
1 A
2 B
3 B
4 C
5 D

I want it to become as follows:

  V1
1 A_1
2 B_1
3 B_2
4 C_1
5 D_1

Is there any function or package that can help me achieve this goal?

CodePudding user response:

First, group_by the variable V1 and then paste together V1 and the line number n().

library(dplyr)
dat %>% group_by(V1) %>% mutate(V1 = paste(V1, row_number(), sep="_"))
# A tibble: 5 × 1
# Groups:   V1 [5]
  V1   
  <chr>
1 A_1  
2 B_1  
3 B_2  
4 C_1  
5 D_1  

CodePudding user response:

you looking for this?

mat<-matrix(data = c("a", "b", "c"))
mat<-paste0(mat, "_", seq(mat))
as.data.frame(mat)
    
  mat
1 a_1
2 b_2
3 c_3

CodePudding user response:

A base solution:

 transform(df, V1 = paste0(V1, "_",ave(rep(1, nrow(df)), V1, 
                                          FUN = seq_along)
                               ))
   V1
1 A_1
2 B_1
3 B_2
4 C_1
5 D_1

One can also do the same with within.

within(df, {V1 = paste0(V1, "_",ave(rep(1, nrow(df)), V1, 
                                          FUN = seq_along)
                              )})
  •  Tags:  
  • r
  • Related