Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

vector

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   
like image 321
Chares Avatar asked Sep 13 '10 10:09

Chares


People also ask

What is the difference between Rbind and Cbind?

cbind() and rbind() both create matrices by combining several vectors of the same length. cbind() combines vectors as columns, while rbind() combines them as rows. Let's use these functions to create a matrix with the numbers 1 through 30.

What is the function of Rbind () in R programming?

rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows. deparse. level: This value determines how the column names generated. The default value of deparse.

Can you Cbind multiple columns in R?

You can use cbind() function in R to bind multiple columns with ease. It is also a function having a simple syntax as well. You can bind data frames, vectors and multiple columns using this function.


1 Answers

The trick is to make all your inputs the same length.

x <- 1:2 y <- 1:10 n <- max(length(x), length(y)) length(x) <- n                       length(y) <- n 

If you want you output to be an array, then cbind works, but you get additional NA values to pad out the rectangle.

cbind(x, y)        x  y  [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 

To get rid of the NAs, the output must be a list.

Map(function(...)     {       ans <- c(...)       ans[!is.na(ans)]    }, as.list(x), as.list(y) ) [[1]] [1] 1 1  [[2]] [1] 2 2  [[3]] [1] 3  [[4]] [1] 4  [[5]] [1] 5  [[6]] [1] 6  [[7]] [1] 7  [[8]] [1] 8  [[9]] [1] 9  [[10]] [1] 10 

EDIT: I swapped mapply(..., SIMPLIFY = FALSE) for Map.

like image 164
Richie Cotton Avatar answered Oct 06 '22 04:10

Richie Cotton