Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two arrays in R

I have two arrays.

Using numpy.append we can merge two arrays.

How can we do same thing in R?

merge can not do that.

Python Output/Example:

   a=np.array([1,2,3,4,5,5])
   b=np.array([0,0,0,0,0,0])
   np.append(a,b)

   array([1, 2, 3, 4, 5, 5, 0, 0, 0, 0, 0, 0])   # this is what I want

x<-c(mat , (0.0) * (l - length(demeaned)))

mat is matrix (size is 20)

l - length(demeaned) is 10

i want at the end 30 size

like image 510
Jose Avatar asked Oct 14 '25 15:10

Jose


2 Answers

The c-function concatenates its arguments. A vector can be a concatenation of numbers or of other verctors:

a = c(1,2,3,4,5,5)
b = c(0,0,0,0,0,0)
c(a,b)

 [1] 1 2 3 4 5 5 0 0 0 0 0 0

At least for one-dimensional arrays like in your python-example this is equivalent to np.append

like image 103
ascripter Avatar answered Oct 17 '25 06:10

ascripter


Adding to the previous answer, you can use rbind or cbind to create two-dimensional arrays (matrices) from simple arrays (vectors):

cbind(a,b)

# output
 a b
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 5 0
[6,] 5 0

or

rbind(a,b)

# output
[,1] [,2] [,3] [,4] [,5] [,6]
a    1    2    3    4    5    5
b    0    0    0    0    0    0

If you want to convert it back to vector, use as.vector. This

as.vector(rbind(a,b))

will give you a joined vector with alternating elements.

Also, note that c can flatten lists if you use the recursive=TRUE argument:

a <- list(1,list(1,2,list(3,4)))
b <- 10
c(a,b, recursive = TRUE)

# output
[1]  1  1  2  3  4 10

Finally, you can use rep to generate sequences of repeating numbers:

rep(0,10)
like image 44
slava-kohut Avatar answered Oct 17 '25 06:10

slava-kohut