[R] repeat a sequence - but not for a full number of times
Sarah Goslee
sarah.goslee at gmail.com
Thu Jul 21 00:27:55 CEST 2011
Or you could take advantage of R's automatic recycling:
> x$b <- rep(1:3, length=nrow(x))
> x
a b
1 1 1
2 2 2
3 3 3
4 4 1
5 5 2
6 6 3
7 7 1
8 8 2
9 9 3
10 10 1
Thanks for providing a simple reproducible example.
Sarah
On Wed, Jul 20, 2011 at 6:20 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote:
> Never mind - found it:
>
> x<-data.frame(a=1:10)
> x$b<-rep(1:3,nrow(x)%/%3,len=nrow(x))
>
> Dimitri
>
> On Wed, Jul 20, 2011 at 6:15 PM, Dimitri Liakhovitski
> <dimitri.liakhovitski at gmail.com> wrote:
>> Apologies, for a very simple question. I forgot how to do it -
>> although I remember reading about getting a warning in such a
>> situation.
>>
>> I have a data frame. It happens to be 10 rows but it could be 11 or 3 or 13...
>> x<-data.frame(a=1:10)
>> I need to add variable "b" that is a sequence of 1:3 - repeated again
>> and again so that the result is:
>> x
>> a b
>> 1 1
>> 2 2
>> 3 3
>> 4 1
>> 5 2
>> 6 3
>> 7 1
>> 8 2
>> 9 3
>> 10 1
>>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list