Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply merge to a list of data.frames

Tags:

merge

r

I have a list of data.frames with just one column and a character value:

> list.df[c(1,5,8)]
$1
     X..1L..
1      A
2      B
3      C
4      D
5      E
6      F
7      G
8      H

$5
   X..5L..
1    A
2    C
3    D
4    F
5    G

$8
   X..8L..
1   A
2   D
3   F
4   G
5   H
6   I

And another data.frame

> df
  V2  V5      V9
1  A  31 0.13029
2  B  80 0.29443
3  C 166 0.01354
4  D  11 0.39589
5  E  62 0.61794
6  F  40 0.35808
7  G  31 0.62581
8  H  54 0.24983
9  I  19 0.47199
10 J  97 0.26518

I would like to merge each data.frame in the list with df, I've tried creating a function func <- function(x,y){merge(x, y, by.x=x[,1], by.y=y[,1])} and then applying it to the list but it does not work.

lapply(list.df, func, list.df, df)

I know that I can split list.df in several data.frames and then merge each of them individually, but I was wondering if there is a way to do it in the list

Thanks

like image 507
user2380782 Avatar asked Jun 13 '13 22:06

user2380782


People also ask

How do I merge a list of DataFrames?

Use pandas. concat() to merge a list of DataFrames into a single DataFrame. Call pandas. concat(df_list) with df_list as a list of pandas.

How do I merge DataFrames in a list in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.

How do I merge 3 data frames in pandas?

We can use either pandas. merge() or DataFrame. merge() to merge multiple Dataframes. Merging multiple Dataframes is similar to SQL join and supports different types of join inner , left , right , outer , cross .

Can you merge multiple DataFrames in pandas?

Pandas' merge and concat can be used to combine subsets of a DataFrame, or even data from different files. join function combines DataFrames based on index or column. Joining two DataFrames can be done in multiple ways (left, right, and inner) depending on what data must be in the final DataFrame.


1 Answers

You have two mistakes. One in your function and the other one in how you call your function:

func <- function(x,y){merge(x, y, by.x=names(x)[1], by.y=names(y)[1])}
lapply(list.df, func, df)
like image 56
eddi Avatar answered Sep 25 '22 20:09

eddi