r - 为向量中的半连续字符串添加运行计数器
问题描述
我想添加一个数字,表示向量中第 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 包?
解决方案
您仍然可以使用row_number()
fromdplyr
但您不需要转换为数据框,即
sub('1$', '', ave(words, words, FUN = function(i) paste0(i, row_number(i))))
#[1] "book" "ship" "umbrella" "book2" "ship2" "ship3"
另一种选择是使用make.unique
withgsubfn
将您的值增加 1,即
library(gsubfn)
gsubfn("\\d+", function(x) as.numeric(x) + 1, make.unique(words))
#[1] "book" "ship" "umbrella" "book.2" "ship.2" "ship.3"
推荐阅读
- django - Django:仅当用户提交表单或保存模型时才允许用户进一步访问
- python - AWS Glue 执行者死亡
- c# - Atata:如何跳过 NoSuchElementException?
- docker - 将 filebeat 连接到 Kibana
- jenkins - 如果 Maven 测试失败,如何使声明性 Jenkins 管道失败?
- javascript - 来自 AJAX 的 .NET Core 控制器输入始终为空
- firebase - 在 Firebase 子目录中添加 Ghost 博客
- python-3.x - Python3没有根据另一个字典正确排序列表
- python - Python2 base64 严格解码仍然默默地忽略无效字符
- c# - 使用 BackgroundWorker 填充 ListView:UI 元素不属于线程