1

I have a 2 lists of 6 data frames each.

listofdf_1 <- list(a, b, c, d, e, f)
listofdf_2 <- list(a2, b2, c2, d2, e2, f2)

I want to inner_join data frame a with a2, b with b2, c with c2 etc. The join column is : ID1

I've written a function :

merge_on_id <- function(x, y, join_field) {
  require(dplyr)
  inner_join(x, y, by = join_field)
} 

Now I'm joining one by one: merge_on_id(listofdf_1[[1]], listofdf_2[[1]], by = "ID1") etc.

I'm wondering if there is a way to join all six in a single line instead of having to repeat for each element of the list.

1 Answer 1

1

If we need to inner_join corresponding elements of lists, we can use Map.

 Map(inner_join, listofdf_1, listofdf_2, MoreArgs=list(by='ID1'))

data

listofdf_1 <- list(a= data.frame(ID1= LETTERS[1:3], Value= 1:3, stringsAsFactors=FALSE),
          b = data.frame(ID1= LETTERS[4:7], V1= 4:7, stringsAsFactors=FALSE))

listofdf_2 <- list(a2= data.frame(ID1= LETTERS[1:5], Value= 6:10, stringsAsFactors=FALSE), 
      b2 = data.frame(ID1= LETTERS[4:9], V1= 4:9, stringsAsFactors=FALSE))
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! the inner join in MAP, is it from dplyr or is it base?
@vagabond It's a base R option, but we could do this with dplyr, possibly in a couple of steps (I thought you wanted a single step answer).
@vagabond It depends upon the number of steps. Also, you can check the speed using system.time or microbenchmark.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.