Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining data frames from two lists

Tags:

r

I have two lists of data frames. In each list a data frame has a column with the same name and values. As an example:

x <- list(data.frame(i=as.character(1:5),x=rnorm(5),z=rnorm(5)),
          data.frame(i=as.character(1:5),x=rnorm(5),z=rnorm(5)))

y <- list(data.frame(i=as.character(5:1),x1=rnorm(5),z1=rnorm(5)),
          data.frame(i=as.character(5:1),x1=rnorm(5),z1=rnorm(5)))

I would like to combine the two lists into one so that each element of the new list is a data frame with the following columns: i, x, z, x1, z1). That is I would like a list of two data frames each with five rows and the five columns I mentioned. I could not find a solution to this (for example, found how to concatenate dfs in a list in one df). I thought to use lapply and pass the function merge(x,y, by= i), but I do not know what the first argument (I.e. data used) should be. Please note that the values in the common column are not in the same order (in the example they are reversed but in my data they are mixed). So let me know if your solution would require ordering the column first. Thanks.

like image 349
Vasile Avatar asked Jun 05 '21 15:06

Vasile


1 Answers

library(tidyverse)
map2(x, y, ~left_join(.x, .y, by = 'i'))
#> [[1]]
#>   i          x         z         x1         z1
#> 1 1 -0.8773188  1.204293  1.2809946  0.9016632
#> 2 2 -0.4091583 -1.128325  0.7973242 -0.1010260
#> 3 3  1.3747095  0.784787 -1.6927698 -1.1568878
#> 4 4  0.7565917 -1.104594  1.0663122 -0.1439810
#> 5 5  0.9662782 -1.039493 -0.2620102 -0.4941850
#> 
#> [[2]]
#>   i         x          z         x1          z1
#> 1 1 0.7871544 -1.0974764  1.2926863  0.99399623
#> 2 2 1.3705341 -0.1047783  1.3612606 -0.01155390
#> 3 3 0.9984027 -0.2466980  0.4554107 -1.38307942
#> 4 4 0.7096952  0.7500738 -0.4586198  0.02311739
#> 5 5 0.1883204 -0.6399546  0.1496794 -0.43233764

Its baseR equivalent

Map(function(.x, .y) merge(.x, .y, by = 'i'), x, y)
#> [[1]]
#>   i            x           z         x1         z1
#> 1 1  1.163081705  0.71855088  0.7981572  0.1029179
#> 2 2  0.876645119 -0.08615626  0.7299087  0.9782025
#> 3 3 -1.460452798 -0.14551233 -0.3380226 -1.1168602
#> 4 4 -0.004574267 -0.36117459  0.2183281 -0.9045827
#> 5 5 -0.836010524  0.12336598 -0.9046551 -0.2670896
#> 
#> [[2]]
#>   i          x          z          x1         z1
#> 1 1 -1.1605742  0.3233873 -0.16685367 -1.0579590
#> 2 2  1.5723944  0.5120253 -0.66373500  0.3241323
#> 3 3 -1.5562135  1.1251436  0.06805823 -2.2889400
#> 4 4  0.2782484  0.4134606 -0.11763939 -0.9060669
#> 5 5 -0.4821373 -0.7170258  0.72466946 -1.4457480

Created on 2021-06-05 by the reprex package (v2.0.0)

like image 173
AnilGoyal Avatar answered Sep 28 '22 15:09

AnilGoyal