擅长:python、mysql、java
<p>在<code>dplyr</code>和<code>paste()</code>中按组创建计数器-1可以为您提供所需的结果:</p>
<pre><code>library(dplyr)
library(tidyr)
# Getting those whose value which Are repeated
df$BoolDup<-duplicated(df$SM)
# Creating counting variable and a second counter that keeps track of the repetitions-1 to then Join if duplicated
df %>% mutate(count = 1) %>%
group_by(SM)%>%
mutate(count2 = cumsum(count)-1) %>%
mutate(DM = ifelse(BoolDup==TRUE,paste(SM,"_",count2,sep =""), SM))%>%
dplyr::select(SM=SM, DM=DM)
# A tibble: 8 x 2
# Groups: SM [4]
# SM DM
# <chr> <chr>
# 1 AB AB
# 2 AC AC
# 3 AD AD
# 4 AB AB_1
# 5 AB AB_2
# 6 AC AC_1
# 7 AE AE
# 8 AD AD_1
</code></pre>