Sequentially perform the same operation on a list of objects in R

Viewed 14

I eventually used the right search terms to find purrr::reduce. Please see these questions/answers: https://stackoverflow.com/search?q=%5Br%5D+reduce+purrr

I have voted to close this question (rather than deleting it) in case my phrasing helps people find the reduce function.

I'm pretty sure this is a duplicate question, since I think I've seen it asked/answered. I have some data frames I want to join on a column "gene":

a <- data.frame(gene = c("a", "b", "c"), old = c(1:3)), 
b <- data.frame(gene = c("c", "b", "a"), new = c(10:13)), 
c <- data.frame(gene = c("a", "c", "a"), bet = c(100:103))

If the genes were in the same order I could use do.call(cbind, list(a, b, c)) and then clean things up. But since the genes are in different orders (and some genes may be missing from some data frames), I want to use dplyr::full_join.

I believe there is a magic_function similar to do.call that takes as arguments a function what (which takes 2 arguments), a list of arguments that will be sequentially passed to the function what, and any additional arguments to function what, so that tmp2 == tmp3 is TRUE for the following example:

tmp1 <- dplyr::full_join(a, b, by = "gene")
tmp2 <- dplyr::full_join(tmp1, c, by = "gene")
tmp3 <- magic_function(dplyr::full_join, list(a, b, c), by = "gene")

Does magic_function exist? Thanks.

Using purrr::reduce:

tmp3 <- purrr::reduce(
  list(a, b, c), 
  function(x, y) dplyr::full_join(x, y, by = "gene")
)
0 Answers
Related