r - Add a column by row names for the different length -


i have found 2 post here, has partial solution of problem. first here , second here.

i have little bit different situation. have list of data frames different length, want join 1 data frame regarding row names. if, row name not in data frame, column should have nan value.

for example have next 3 data frames:

mylist[1] -> df1:

    num   1 b   1 

mylist[2] -> df2:

    num   1 b   2 c   3 d   1 

mylist[3] -> df3:

    num c   1 d   1 

what want have next dataframe:

   num1   num2  num3  1      1     nan b  1      2     nan c  nan    3     1 d  nan    1     1 

it means, nan values on right place , not @ bottom of column, in first example. length of dataframes different , not same in second example.

i in 2 steps:

1) add id-column containing rownames:

mylist <- lapply(mylist, function(x) transform(x, id = row.names(x))) 

2) merge data.frame's id-column:

reduce(function(...) merge(..., = "id", all=true), mylist) #  id num.x num.y num #1      1     1  na #2  b     1     2  na #3  c    na     3   1 #4  d    na     1   1 

this kind of approach valuable if have many items in mylist since don't have type each merge command manually.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -