[R] Combine by columns a vector with another vector that is constant across rows

Viechtbauer, Wolfgang (SP) wo||g@ng@v|echtb@uer @end|ng |rom m@@@tr|chtun|ver@|ty@n|
Tue Jul 3 19:12:58 CEST 2018

Thanks for all of the suggestions. I did some benchmarking:


x <- 1:5
vec <- c(2,4,3)

fastWolfgang <- function(v, vec)
   matrix(c(v, rep(vec, each = length(v))), nrow = length(v))

microbenchmark(cbind(x, t(replicate(length(x), vec))),
               t(sapply(x, function(x) c(x, vec))),
               do.call(rbind, lapply(x, function(x) c(x, vec))),
               t(mapply(c, x, MoreArgs=list(vec))),
               Reduce(cbind, vec, x),
               Reduce(cbind2, vec, x),
               fastWolfgang(x, vec), times=10000L)

Jeff's approach is fastest, but Gabor's Reduce(cbind, vec, x) is close (and I really like its simplicity); and very similar to the do.call() approach.

Interestingly, for larger vectors, such as:

x <- 1:50
vec <- sample(1:100, 200, replace=TRUE)

the do.call() approach is the fastest.


>-----Original Message-----
>From: Jeff Newmiller [mailto:jdnewmil using dcn.davis.ca.us]
>Sent: Tuesday, 03 July, 2018 17:48
>To: r-help using r-project.org; Viechtbauer, Wolfgang (SP); r-help using r-
>Subject: Re: [R] Combine by columns a vector with another vector that is
>constant across rows
>Sorry trying again...
>fastWolfgang <- function( v, vec ) {
>  matrix( c( v, rep( vec, each = length( v ) ) )
>         , nrow = length( v ) )
>On July 3, 2018 8:21:47 AM PDT, Jeff Newmiller <jdnewmil using dcn.davis.ca.us>
>>Gabor's solution seems to optimize 'simpler'.
>>More efficient is to learn that in R a vector is not a matrix, but a
>>matrix is just an ornamented vector.
>>fastWolfgang <- function( v, vec ) {
>>  matrix( c( v, rep( vec, length( v ) ) )
>>         , now = length( v ) )
>>On July 3, 2018 6:28:45 AM PDT, "Viechtbauer, Wolfgang (SP)"
>><wolfgang.viechtbauer using maastrichtuniversity.nl> wrote:
>>>Hi All,
>>>I have one vector that I want to combine with another vector and that
>>>other vector should be the same for every row in the combined matrix.
>>>This obviously does not work:
>>>vec <- c(2,4,3)
>>>cbind(1:5, vec)
>>>This does, but requires me to specify the correct value for 'n' in
>>>cbind(1:5, t(replicate(5, vec)))
>>>Other ways that do not require this are:
>>>t(sapply(1:5, function(x) c(x, vec)))
>>>do.call(rbind, lapply(1:5, function(x) c(x, vec)))
>>>t(mapply(c, 1:5, MoreArgs=list(vec)))
>>>I wonder if there is a simpler / more efficient way of doing this.

More information about the R-help mailing list