Search code examples
rplyrdplyrmutated

Mutate dataframes by matching ids in r


I have three data frames:

df1:

id score1
1   50
2   23
3   40
4   68
5   82
6   38

df2:

id score2
1   33
2   23
4   64
5   12
6   32

df3:

id score3
1   50
2   23
3   40
4   68
5   82

I want to mutate the three scores to a dataframe like this, using NA to denote the missing value

id score1 score2 score3
1   50     33     50
2   23     23     23
3   40     NA     40
4   68     64     68
5   82     12     82
6   38     32     NA

Or like this, deleting the NA values:

id score1 score2 score3
1   50     33     50
2   23     23     23
4   68     64     68
5   82     12     82

However, mutate (in dplyer) does not take different length. So I can not mutate. How can I do that?


Solution

  • You can try

      Reduce(function(...) merge(..., by='id'), list(df1, df2, df3))
      #   id score1 score2 score3
      #1  1     50     33     50
      #2  2     23     23     23
      #3  4     68     64     68
      #4  5     82     12     82
    

    If you have many dataset object names with pattern 'df' followed by number

      Reduce(function(...) merge(..., by='id'), mget(paste0('df',1:3)))
    

    Or instead of paste0('df', 1:3), you can use ls(pattern='df\\d+') as commented by @DavidArenburg