在向量中按组递增的后缀

时间:2018-02-06 03:56:10

标签: r

嗨,假设我有一个矢量:

v <- c( "k", "k", "c", "c", "k", "c")
#I can suffix this by doing a paste
paste0 (v,"1")
"k1" "k1" "c1" "c1" "k1" "c1"

但是有没有办法逐步向每个组添加一个? 我想要的是下面没有循环。

"k1" "k2" "c1" "c2" "k3" "c3"

这可能吗?

2 个答案:

答案 0 :(得分:5)

我们可以将基数R aveseq_along一起使用来计算v中每个唯一值的出现次数以及paste后缀的出现次数。

ave(v, v, FUN = function(x) paste0(x, seq_along(x)))
#[1] "k1" "k2" "c1" "c2" "k3" "c3"

或者更紧凑:

paste0(v, ave(v, v, FUN = seq_along))
#[1] "k1" "k2" "c1" "c2" "k3" "c3"

答案 1 :(得分:3)

我们可以使用make.unique,它将为每个重复的元素增加

make.unique(v, sep="")
#[1] "k"  "k1" "c"  "c1" "k2" "c2"