我正在使用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"
答案 0 :(得分:8)
我很惊讶ave
还没有到来:
> paste0(letters[y], ave(y, y, FUN=seq_along))
[1] "a1" "a2" "a3" "a4" "b1" "b2" "c1" "c2" "c3" "d1" "d2" "d3"
答案 1 :(得分: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"