首页 > 解决方案 > 为向量中的半连续字符串添加运行计数器

问题描述

我想添加一个数字,表示向量中第 x 次出现的单词。(所以这个问题与Make a column with duplicate values unique in a dataframe不同,因为我有一个简单的向量并尽量避免将其转换为 data.frame 的开销)。

例如对于向量:

book, ship, umbrella, book, ship, ship

输出将是:

book, ship, umbrella, book2, ship2, ship3

我自己解决了这个问题,方法是将向量转置到数据框,然后使用分组函数。这感觉就像用大锤敲碎坚果:

# add consecutive number for equal string
words <- c("book", "ship", "umbrella", "book", "ship", "ship")

# transpose word vector to data.frame for grouping
df <- data.frame(words = words)
df <- df %>% group_by(words) %>% mutate(seqN = row_number())

# combine columns and remove '1' for first occurrence
wordsVec <- paste0(df$words, df$seqN)       
gsub("1", "", wordsVec)
# [1] "book"     "ship"     "umbrella" "book2"    "ship2"    "ship3"   

有没有更干净的解决方案,例如使用 stringr 包?

标签: rcountstringrfind-occurrences

解决方案


您仍然可以使用row_number()fromdplyr但您不需要转换为数据框,即

sub('1$', '', ave(words, words, FUN = function(i) paste0(i, row_number(i))))
#[1] "book"     "ship"     "umbrella" "book2"    "ship2"    "ship3"

另一种选择是使用make.uniquewithgsubfn将您的值增加 1,即

library(gsubfn)
gsubfn("\\d+", function(x) as.numeric(x) + 1, make.unique(words))
#[1] "book"     "ship"     "umbrella" "book.2"   "ship.2"   "ship.3"

推荐阅读