Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Assign a serial number to duplicated values of a vector in R

I would like to assign a serial number to duplicated values of a vector in R without using a for loop as shown in the example below. I have a big data set. Thanks

a<-c("A","B","A","A","B","C","D","E","D")

Expected Output:

desired.answer<-c(1,1,2,3,2,1,1,1,2)
question from:https://stackoverflow.com/questions/65944871/assign-a-serial-number-to-duplicated-values-of-a-vector-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the data you provided you can use the group_by function from the dplyr package to then assign serial numbers independently to each group.

data.frame(value = c("A","B","A","A","B","C","D","E","D") ) %>% 
  group_by(value) %>% 
  mutate(serial_number = 1:n())
A tibble: 9 x 2
Groups:   value [5]
 value serial_number
 <chr>         <int>
1 A                 1
2 B                 1
3 A                 2
4 A                 3
5 B                 2
6 C                 1
7 D                 1
8 E                 1
9 D                 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...