Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Two Arrays in R

Tags:

arrays

merge

r

Suppose I have two arrays, array1 and array2, that look like

array1

        45    46   47    48    49    50
        1.0   1.5  1.3   1.2   0.9   1.1

array2

        45    46   47    48    49    50
        2.5   5.5  4.5   5.8   1.5   8.4

and I want to merge them into a data frame that looks like:

       1.0  2.5
       1.5  5.5
       1.3  4.5
       1.2  5.8
       0.9  1.5
       1.1  8.4

The numbers 45 to 50 don't matter.

like image 903
user2543427 Avatar asked Aug 23 '13 16:08

user2543427


People also ask

How do I combine two arrays?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.

How do I combine two arrays from another array?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I merge two arrays into a single sorted array?

Merge Sort MethodCreate an auxiliary array of size N + M and insert the merge element in this array. Create an auxiliary array of size N + M. Put two pointers i and j and initialise them to 0. Pointer i points to the first array, whereas pointer j points to the second array.


1 Answers

 array1 <- c(1.0,1.5,1.3,1.2,0.9,1.1)
 array2 <- c(2.5,5.5,4.5,5.8,1.5,8.4)

 result = cbind(array1, array2)

In case you don't want to see any column names or row names (as posted in your question), you should do the following:

 result = as.matrix(cbind(array1, array2)) 
 dimnames(result) <-list(rep("", dim(result)[1]), rep("", dim(result)[2]))

You get:

 > result

  1.0 2.5
  1.5 5.5
  1.3 4.5
  1.2 5.8
  0.9 1.5
  1.1 8.4
like image 56
Mayou Avatar answered Oct 23 '22 13:10

Mayou