Reduce

Published by onesixx on

https://stackoverflow.com/questions/26220730/how-to-merge-a-list-of-dataframes-by-a-single-column

https://stat.ethz.ch/pipermail/r-help/2012-January/301984.html
dd <- list(df1=data.frame(Name=LETTERS[1:3], Sample1=1:3, stringsAsFactors=F),
           df2=data.frame(Name=LETTERS[1:3], Sample2=4:6, stringsAsFactors=F),
           df3=data.frame(Name=LETTERS[1:3], Sample3=7:9, stringsAsFactors=F))
$df1
  Name Sample1
1    A       1
2    B       2
3    C       3

$df2
  Name Sample2
1    A       4
2    B       5
3    C       6

$df3
  Name Sample3
1    A       7
2    B       8
3    C       9
# with by="Name"
merged.df <- Reduce( function(...) merge(..., by="Name", all=T), dd)

# without by="Name" (same result)
merged.df <- Reduce( function(...) merge(..., all=T), dd)
  Name Sample1 Sample2 Sample3
1    A       1       4       7
2    B       2       5       8
3    C       3       6       9

Multi-vector

https://www.r-bloggers.com/intersect-for-multiple-vectors-in-r/

Reduce(intersect, list(a,b,c))

Reduce(union, list(x, y, z))

reduce()
combine from the left

> a <- c(1:3)
> b <- c(3:5)
> c <- c(5:7)
> Reduce(union, list(a,b,c))
[1] 1 2 3 4 5 6 7
dd <- list(df1=data.frame(value=1:5, name=c("A","B","C","D","E"),     id=111, stringsAsFactors=F),
+            df2=data.frame(value=1:5, name=c("A","B","C","F","E"),     id=222, stringsAsFactors=F),
+            df3=data.frame(value=1:6, name=c("A","Z","C","Y","E","F"), id=333, stringsAsFactors=F),)



Categories: Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x