0

I am trying to run a function that takes value1, value2, value3 of the same time and name from multiple data frames. output <- function(value1, value2, value3) For example:

DF1:
time       name      value1
Jan 1990      1      4
Feb 1990      1      2
Mar 1990      1      3
Jan 1990      2      2
Feb 1991      2      1
DF2:
time       name      value2
Jan 1990      1      4
Feb 1990      1      2
Mar 1990      1      3
Jan 1990      2      2
Feb 1991      2      1
DF3:
time       name      value3
Jan 1990      1      4
Feb 1990      1      2
Mar 1990      1      3
Jan 1990      2      2
Feb 1991      2      1

Should I use join and then apply on each row?

output
time       name    output 
Jan 1990      1      4
Feb 1990      1      2
Mar 1990      1      3
Jan 1990      2      2
Feb 1991      2      1
YellowRiver
  • 65
  • 1
  • 7

1 Answers1

0

Use -

Option 1: dplyr library(dplyr)

output <- inner_join(inner_join(df1, df2, by=c("time", "name")), 
                 df3, by=c("time", "name"))

Option 2: plyr

library(plyr)
join_all(list(df1,df2,df3), by=c('time','name'), type='inner')           

Option 3: Base R merge+reduce

Use merge + reduce - credits to @akrun

Reduce(function(...) merge(..., by=c("time","name"), all.x=TRUE), list(df1,df2,df3))

Output

      time name value1
1 Jan 1990    1      4
2 Feb 1990    1      2
3 Mar 1990    1      3
4 Jan 1990    2      2
5 Feb 1991    2      1

You can then rename the columns as per your necessity.

Vivek Kalyanarangan
  • 8,951
  • 1
  • 23
  • 42