Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively repeat vector elements N times each [duplicate]

Tags:

r

I want to repeat a vector N times but element-wise, not the whole vector.

For instance, I have:

v <- c('a', 'b') 

Say I want to repeat n times:

n <- 3 

I want:

vfill <- c(rep(v[1], n), rep(v[2], n)) print(vfill) [1] "a" "a" "a" "b" "b" "b" 

My best solution to date:

ffillv <- function(i) rep(v[i], n) c(sapply(seq_len(length(v)), ffillv)) 

I am interested in fast & scalable solutions, for instance using rbind, plyr, etc.

like image 628
Patrick Avatar asked Feb 28 '13 17:02

Patrick


People also ask

How do you repeat a vector element in R?

There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.

How do you repeat a number multiple times in R?

The way to repeat rows in R is by using the REP() function. The REP() function is a generic function that replicates the value of x one or more times and it has two mandatory arguments: x: A vector. For example, a row of a data frame.

What is R rep function?

In simple terms, rep in R, or the rep() function replicates numeric values, or text, or the values of a vector for a specific number of times.


1 Answers

rep(v, each=3) 

or

rep(v, each=n) 

where you have n defined

like image 129
larrydag Avatar answered Sep 30 '22 09:09

larrydag