我有一个带有如下字符元素的向量:
vec <- c("A", "A", "A", "B", "B", "B", "C", "C", "C")
我想为vec
中的每个元素添加一个后缀,表示元素重复的次数,输出应该是这样的:
>vec1
[1] "A_1" "A_2" "A_3" "B_1" "B_2" "B_3" "C_1" "C_2", "C_3"
我尝试过以下但不起作用
sapply(vec, function(x) paste(x, seq(1,3,1), sep="_"))
答案 0 :(得分:3)
如何使用粘贴:
# dynamic version
paste(vec,
unlist(sapply(as.numeric(table(vec)),
function(i) seq(1,i,1))),
sep="_")
当我们不知道每封信重复多少次时。
paste(vec,sequence(rle(vec)$lengths), sep="_")
由于@Jay建议更简单的动态版
foreach
答案 1 :(得分:1)
即使“A”,“B”等的数字不同,这也有效:
vec <- c(rep("A",3),rep("B",5),rep("C",2))
n <- c("",vec[-length(vec)]) != vec
m <- (1:length(vec)) * n
idx <- (1:length(vec))-cummax(m)+1
v <- paste(vec,idx,sep="_")
> vec
[1] "A" "A" "A" "B" "B" "B" "B" "B" "C" "C"
> n
[1] TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE
> m
[1] 1 0 0 4 0 0 0 0 9 0
> idx
[1] 1 2 3 1 2 3 4 5 1 2
> v
[1] "A_1" "A_2" "A_3" "B_1" "B_2" "B_3" "B_4" "B_5" "C_1" "C_2"
>
相反:
> paste(vec,1:3,sep="_")
[1] "A_1" "A_2" "A_3" "B_1" "B_2" "B_3" "B_1" "B_2" "C_3" "C_1"
>