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

Categories

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

Adding a increment value in column in R

enter image description here

I need to add a value next to name for example in image Ashish 1. I want to add a value like 1,2 3,4,5. there are 500 enteries in total

I used this code to change first 20 but i want to change it for all 500

customer$name[1:10] = names

names=c('Ashish1','Alok1','Ricky1','Sagar1','Meet1','Sameer1','Surbhi1','Yash1','Sandeep1','Mohsin1')
customer$name[11:20] = names

Please execuse still not use to add things properly.


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

1 Answer

0 votes
by (71.8m points)

Do you want to increment every duplicate? Such that c("Ashish","Ricky","Sagar","Ashish","Sagar","Ashish","Ricky") gets changed to c("Ashish1","Ricky1","Sagar1","Ashish2","Sagar2","Ashish3","Ricky2")?

I've opted to increase all customer names (is there a reason only the very first should not be added an incremented value?) simply because it's easier. But I will show that once we can do that, it is easy to only add to every subsequent:

Introducing the package dplyr:

customer %>% group_by(name) %>%
  mutate(i = 1:n()) %>% ungroup %>%
  mutate(name = paste0(name, i)

If you have any ordering to determine which name is the "first", e.g. customerId, add arrange(customerId) %>% after the first group_by.

Now that we have added an increasing number, let's modify it, so the very first is not modified:

customer %>% group_by(name) %>%
  mutate(i = 1:n()) %>% ungroup %>%
  mutate(name = ifelse(i > 1, paste0(name, i), name))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...