Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating table with average column values given row "matches" in R

Tags:

r

I'm hoping someone can help me with this problem. Let's say I have to data frames like the ones below.

      A     B     C     D
1     1     1    10   100
2     2     1    30   200
3     1     2    30   200
4     2     2    10   400

      A     B     C     D
1     1     1    10   300
2     2     1    20   400
3     1     2    30   300
4     2     2    20   600

My desired result is creating a combined frame with average values in columns C and D given a complete combined match of values in columns A and B, yielding a frame that looks like this:

      A     B     C     D
1     1     1    10   200
2     2     1    25   300
3     1     2    30   250
4     2     2    15   500

Anyone know a snippet of code that will help me in this pinch?

like image 348
TiberiusGracchus2020 Avatar asked Dec 23 '22 20:12

TiberiusGracchus2020


1 Answers

One base R option could be:

aggregate(cbind(C, D) ~ ., FUN = mean, data = rbind(df1, df2))

  A B  C   D
1 1 1 10 200
2 2 1 25 300
3 1 2 30 250
4 2 2 15 500
like image 157
tmfmnk Avatar answered Feb 22 '23 23:02

tmfmnk