嗨,假设我有一个矢量:
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"
这可能吗?
答案 0 :(得分:5)
我们可以将基数R ave
与seq_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"