为向量中的半连续字符串添加 运行 计数器
add running counter for semi-consecutive strings in vector
我想添加一个数字,表示一个词在向量中出现的第 x^ 次。 (所以这个问题不同于 ,因为我有一个简单的向量并尽量避免将其转换为 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 包?
您仍然可以使用 dplyr
中的 row_number()
,但您不需要转换为数据框,即
sub('1$', '', ave(words, words, FUN = function(i) paste0(i, row_number(i))))
#[1] "book" "ship" "umbrella" "book2" "ship2" "ship3"
另一种选择是使用 make.unique
和 gsubfn
将您的值增加 1,即
library(gsubfn)
gsubfn("\d+", function(x) as.numeric(x) + 1, make.unique(words))
#[1] "book" "ship" "umbrella" "book.2" "ship.2" "ship.3"
我想添加一个数字,表示一个词在向量中出现的第 x^ 次。 (所以这个问题不同于
例如对于向量:
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 包?
您仍然可以使用 dplyr
中的 row_number()
,但您不需要转换为数据框,即
sub('1$', '', ave(words, words, FUN = function(i) paste0(i, row_number(i))))
#[1] "book" "ship" "umbrella" "book2" "ship2" "ship3"
另一种选择是使用 make.unique
和 gsubfn
将您的值增加 1,即
library(gsubfn)
gsubfn("\d+", function(x) as.numeric(x) + 1, make.unique(words))
#[1] "book" "ship" "umbrella" "book.2" "ship.2" "ship.3"