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.
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.
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.
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.
rep(v, each=3)
or
rep(v, each=n)
where you have n defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With