3

I'm trying to calculate an average across groups, but leaving the observation's own group.

My data looks like this:

library(dplyr)

df <- tribble(
  ~year, ~country, ~value,
  2001, "France", 150, 
  2002, "France", 53, 
  2003, "France", 31, 
  2004, "France", 10, 
  2005, "France", 30, 
  2006, "France", 37, 
  2007, "France", 54, 
  2008, "France", 58, 
  2009, "France", 50, 
  2010, "France", 40, 
  2011, "France", 49, 
  2001, "USA", 55,
  2002, "USA", 53,
  2003, "USA", 64,
  2004, "USA", 70,
  2005, "USA", 80,
  2006, "USA", 160,
  2007, "USA", 55,
  2008, "USA", 53,
  2009, "USA", 71,
  2010, "USA", 11,
  2011, "USA", 10,
  2001, "GBR", 12,
  2002, "GBR", 8,
  2003, "GBR", 7,
  2004, "GBR", -5,
  2005, "GBR", NA,
  2006, "GBR", NA,
  2007, "GBR", NA,
  2008, "GBR", 5,
  2009, "GBR", 12,
  2010, "GBR", 16,
  2011, "GBR", 25
)

I have a balanced panel dataset, so the years are the same for all countries.

I would like to define a new column that takes the mean across the values from the other two countries.

So the value for 2001, "France" would be 33.5, the mean of 55 (from 2001, "USA") and 12 (from 2001, "GBR"). My messy real-life dataset is much bigger, so doing this by hand would not be a good idea.

ulima2_
  • 1,276
  • 1
  • 13
  • 23

0 Answers0