如何创建数字循环? [英] How can I create the cycle of numbers?

查看:33
本文介绍了如何创建数字循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using R, and wonder if anyone can help me this. I want to transform this vector:

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)

所以我可以执行以下操作:

So I can do the following:

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"

推荐答案

这里有几个选项:

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"

这篇关于如何创建数字循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆