【问题标题】:add running counter for semi-consecutive strings in vector为向量中的半连续字符串添加运行计数器
【发布时间】:2019-05-16 12:38:10
【问题描述】:

我想添加一个数字,表示一个单词在向量中出现的第 x 次。 (所以这个问题与 Make a column with duplicated 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 包?

【问题讨论】:

  • 您正在寻找make.unique,即简单地make.unique(words)
  • 您不需要将其转换为数据框。如果你看到我之前的评论你就会明白。另外,如果我做make.unique(df$v1)df$v1 无论如何都是一个向量
  • 你不需要分组。你有一个简单的向量,使它更容易使用。
  • 嗨@sotos make.unique(words),实际上并没有回答这个问题:它直接计算连续的单词。例如。按照 OP 的要求,最终船舶出现的编号应为 3,而不是 2。 &gt; make.unique(words) [1] "book" "ship" "umbrella" "book.1" "ship.1" "ship.2"
  • 哦,所以你需要他们从原始值开始计数

标签: r count stringr find-occurrences


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2019-05-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多