Categories
r vector

How to cbind or rbind different lengths vectors without repeating the elements of the shorter vectors?

64

cbind(1:2, 1:10)  
     [,1] [,2]  
  [1,]    1    1  
  [2,]    2    2  
  [3,]    1    3  
  [4,]    2    4  
  [5,]    1    5  
  [6,]    2    6  
  [7,]    1    7  
  [8,]    2    8  
  [9,]    1    9  
 [10,]    2   10  

I want an output like below

[,1] [,2]  
[1,] 1 1  
[2,] 2 2  
[3,]   3  
[4,]   4  
[5,]   5  
[6,]   6  
[7,]   7  
[8,]   8  
[9,]   9  
[10,]  10  

2

  • Yup, this is called recycling and is one of R’s base concepts. What other behavior do you want?

    – mbq

    Sep 13, 2010 at 10:08

  • This seems to have been addressed through time also: here, here and here

    Jan 26, 2018 at 21:37

27

I came across similar problem and I would like to suggest that additional solution that some, I hope, may find useful. The solution is fairly straightforward and makes use of the qpcR package and the provided cbind.na function.

Example

x <- 1:2
y <- 1:10
dta <- qpcR:::cbind.na(x, y)

Results

> head(dta)
      x y
[1,]  1 1
[2,]  2 2
[3,] NA 3
[4,] NA 4
[5,] NA 5
[6,] NA 6

Side comments

Following the OP’s original example, column names can be easily removed:

colnames(dta) <- NULL

the operation would produce the desired output in full:

> head(dta)
     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]   NA    3
[4,]   NA    4
[5,]   NA    5
[6,]   NA    6

2

  • 4

    This solution is particularly elegant when working with more than two data sets. Using do.call(qpcR:::cbind.na, ...) allows to easily cbind a list of data.frames of arbitrary length.

    – fdetsch

    Feb 13, 2017 at 10:54

  • 3

    cbind.na does not exist (anymore?) in the package qpcR

    Aug 5, 2020 at 13:19

7

I would like to propose an alternate solution that makes use of the rowr package and their cbind.fill function.

> rowr::cbind.fill(1:2,1:10, fill = NA);

   object object
1       1      1
2       2      2
3      NA      3
4      NA      4
5      NA      5
6      NA      6
7      NA      7
8      NA      8
9      NA      9
10     NA     10

Or alternatively, to match the OP’s desired output:

> rowr::cbind.fill(1:2,1:10, fill="");

   object object
1       1      1
2       2      2
3              3
4              4
5              5
6              6
7              7
8              8
9              9
10            10

1

  • 5

    rowr was removed from CRAN

    – ACE

    May 10, 2020 at 20:40