1

I try to create a loop that makes join to 5 dataframes like this

c <- list(EC_Pop, EC_GDP, EC_Inflation, ST_Tech_Exp, ST_Res_Jour)

for (i in seq_along(c))
{
  if (i < 2)
  {
    EC_New <- c[i] %>%
      left_join(c[i+1], by = c("Country","Year"))
  }
  else if(i > 1 & i < 4) 
  {
    EC_New <- EC_New %>%
      left_join(c[i+1], by = c("Country","Year"))
  }
  else
  {
    EC_New
  }
}

But I have an error : UseMethod ("left_join") error: No Applicable method for 'left_join' applied to object of class "list"

Can somebody explain the reason? It seems very logical for me the way I wrote it...

1 Answers1

2

According to the documentation of left_join, both x and y must be data frames.

Your c is a list, and so is c[i].

However, c[[i]] is a data frame. So change your code to include two square brackets.

EC_New <- c[[i]] %>%
      left_join(c[[i+1]], by = c("Country","Year"))

I think you can also replace your code using Reduce:

EC_New2 <- Reduce(left_join, c)

Then check:

identical(EC_New, EC_New2) # should be TRUE

But I'm not sure since I don't have your data. It should work if the common columns are only "Country" and "Year".

And thanks to this answer, you can use the following command if the "Country" and "Year" are not the only common columns.

EC_New2 <- Reduce(function(x, y) left_join(x, y, by=c("Country","Year")), c)

By the way, try not to use function names such as c to name your R objects. While R allows this, it can lead to confusion later. For example, if you want to concatenate x and y but accidentally type c[x, y] instead of c(x, y), R may not return an error but something totally unexpected.

Edward
  • 10,360
  • 2
  • 11
  • 26