Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rbind vectors matching their column names?

Tags:

r

rbind

rbind does not check for column names when binding together vectors:

l = list(row1 = c(10, 20), row2 = c(20, 10)) names(l$row1) = c("A", "B") names(l$row2) = c("B", "A") l $row1  A  B  10 20   $row2  B  A  20 10   rbind(l$row1, l$row2)       A  B [1,] 10 20 [2,] 20 10 

How can I produce this matrix from a number of list elements, insuring the column names are correctly matched across rows:

      A  B [1,] 10 20 [2,] 10 20 
like image 929
Robert Kubrick Avatar asked Jun 06 '13 12:06

Robert Kubrick


People also ask

Does Rbind work if columns are in different order?

0), rbind has the capacity to to join two data sets with the same name columns even if they are in different order.

How do I Rbind a column of different numbers?

Method 1 : Using plyr package rbind. fill() method in R is an enhancement of the rbind() method in base R, is used to combine data frames with different columns. The column names are number may be different in the input data frames. Missing columns of the corresponding data frames are filled with NA.

What does Rbind () do in R?

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.

What is the use of Rbind () and Cbind () in R?

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.


1 Answers

It seems that in current versions of R (I have version 3.3.0), rbind has the capacity to to join two data sets with the same name columns even if they are in different order.

   df1 <- data.frame(a = c(1:5), c = c(LETTERS[1:5]),b=c(11:15))    df2 <- data.frame(a = c(6:10), b = c(16:20),c=c(LETTERS[6:10]))    rbind(df1,df2)     a c  b 1   1 A 11 2   2 B 12 3   3 C 13 4   4 D 14 5   5 E 15 6   6 F 16 7   7 G 17 8   8 H 18 9   9 I 19 10 10 J 20 
like image 127
scs76 Avatar answered Sep 29 '22 06:09

scs76