Combining two arrays in R

Suppose I have two arrays: array1 and array2, which 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 combine them into a data frame that looks like this:

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

Numbers 45 to 50 do not matter.

+6
source share
3 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) 

If you do not want to see column names or row names (as indicated 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 are getting:

  > 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 
+8
source

You can combine ?rbind and ?t or just use ?cbind depending on the format of your data.

For instance:

 new.array <- t(rbind(array1,array2)) 

or

 new.array <- cbind(array1,array2) 

or

 new.arrray <- data.frame(array1,array2) 

If you have two vectors, cbind is the best way. However, suppose you have two data frames. i.e:

 array1 <- t(data.frame(array1=c(1.0,1.5,1.3,1.2,0.9,1.1))) array2 <- t(data.frame(array2=c(2.5,5.5,4.5,5.8,1.5,8.4))) 

Using cbind will not give the desired result, and you will need to combine t and rbind .

 > cbind(array1,array2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] array1 1 1.5 1.3 1.2 0.9 1.1 2.5 5.5 4.5 5.8 1.5 8.4 > t(rbind(array1,array2)) array1 array2 [1,] 1.0 2.5 [2,] 1.5 5.5 [3,] 1.3 4.5 [4,] 1.2 5.8 [5,] 0.9 1.5 [6,] 1.1 8.4 
+1
source

You can join in arrays below the given code and can display in the required format.

  for (int i = 45; i <=50; i++) { float[] merge = { array1[i], array2[i] }; } // to display in required format for (int j =0; i <merge.Length; i++) { Console.WriteLine(merge[i]); } 
-2
source

Source: https://habr.com/ru/post/952377/


All Articles