0

I have 2 types (say a and b) of dataframes in my R environment, each with 20 years. I am trying to write a loop in R such that I can merge the 1st dataframe in type a with 1st dataframe in type b by a particular variable.

I have a1,a2,...,a20 and b1,b2,...,b20 in my environment and the common variable by which I am trying to merge is ID. I have tried with the code below, but I am guessing the issue is inside the merge function where I am defining the x and y.

for (i in 1:20) {
  assign(paste0("ab", i), merge(x="a"&i, y="b"&i, by.x = 'ID', by.y='ID', all.x=TRUE))

}

I want to have 20 new dataframes (called ab1, ab2,..., ab20) with the information from type a and b together. Any help will be greatly appreciated and please do point it to me in case there exists a same question.

  • 1
    How did you wind up with all those variables? It's better to store related [data.frames in a list](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames). Then it would be easy just to `Map()` the merge over the two lists. You should avoid `get/assign` when writing R code. There are often more R-like ways to do things. – MrFlick Mar 22 '19 at 18:49
  • Hello @MrFlick, I was trying to merge the elements of 2 lists by their order of being in the list in the first instance, but was unsuccessful. I was not aware of the Map(), I will check that out. Thank you very much. I will keep your advice in mind. – econbuffin2019 Mar 22 '19 at 18:58

1 Answers1

0

How about this:

for (i in 1:20) {
  assign(paste0("ab", i), merge(x=get(paste0("a",i)), y=get(paste0("b",i)), by.x = 'ID', by.y='ID', all.x=TRUE))
LocoGris
  • 3,991
  • 3
  • 13
  • 30
  • But @MrFlick is right. My solution it is not best practice when coding in R. I use it only when I am in a hurry or unable to solve it in a more stylish fashion. – LocoGris Mar 22 '19 at 19:00