• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Repeat Vectors in R

 
Greenhorn
Posts: 4
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How can I repeat vectors in R?
 
Sheriff
Posts: 3063
12
Mac IntelliJ IDE Python VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use the rep function:

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You  can use the rep() function in several ways if you want to repeat the complete vector.
For examples: specify the argument times 1. To repeat the vector c(0, 0, 7) three times,
use this code:

> rep(c(0, 0, 7), times = 4)
[1] 0 0 7 0 0 7 0 0 7 0 0 7 2

We can also repeat every value by specifying the argument each, like this:

> rep(c(2, 4, 2), each = 2)
[1] 2 2 4 4 2 2 3

We can tell R for each value how often it has to repeat:

> rep(c(0, 7), times = c(4,3))
[1] 0 0 0 0 7 7 7 4

In seq, we use the argument length.out to define R. it will repeat the vector until it reaches that length,
even if the last repetition is incomplete.

> rep(1:3,length.out=9)
[1] 1 2 3 1 2 3 1 2 3
 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
R>n<-3
R> rep(1:5,each=n)

Answer is
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just to add to the previous answers, which are all great, you can also repeat character vectors.

 
Marshal
Posts: 79178
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch, KP
 
Karl Peterson
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Welcome to the Ranch, KP



Thanks!
 
reply
    Bookmark Topic Watch Topic
  • New Topic