3

我正在使用 R,想知道是否有人可以帮助我。我想转换这个向量:

y<-c(1,1,1,1,2,2,3,3,3,4,4,4)

y<-c(1,2,3,4,1,2,1,2,3,1,2,3)

所以我可以做到以下几点:

v<-c(rep("a",4), rep("b",2), rep("c",3), rep("d",3)) 
paste (v, y, sep="")
[1] "a1" "a2" "a3" "a4" "b1" "b2" "c1" "c2" "c3" "d1" "d2" "d3"
4

2 回答 2

8

我很惊讶ave还没到:

> paste0(letters[y], ave(y, y, FUN=seq_along))
 [1] "a1" "a2" "a3" "a4" "b1" "b2" "c1" "c2" "c3" "d1" "d2" "d3"
于 2013-10-16T08:53:24.230 回答
5

这里有几个选项:

f1 <- function(x) {
    paste0(letters[x], unlist(tapply(x,x, seq_along)))
}
f1(y)
#  [1] "a1" "a2" "a3" "a4" "b1" "b2" "c1" "c2" "c3" "d1" "d2" "d3"


f2 <- function(x) {
    x <- letters[x]
    ll <- unique(x)
    make.unique(c(ll, x), sep="")[-seq_len(length(ll))]
}
f2(y)
#  [1] "a1" "a2" "a3" "a4" "b1" "b2" "c1" "c2" "c3" "d1" "d2" "d3"
于 2013-10-16T06:33:06.243 回答