0

I want to add an extra column in my already existing dataframe with location, coral type, percent bleached and year as column. I want average of bleach percent of each type of coral on every site over the years. For example, soft corals on site 01 has bleach percent on 20 in 2010 and 10 in 2011 so the average column value will contain 15.

already exiting df

type    location year    value
soft    site01    2010     20
soft    site01    2011     10
hard    site01    2010     10
hard    site01    2011     30

after adding column

type    location year    value  avg
soft    site01    2010     20    15
soft    site01    2011     10    15
hard    site01    2010     10    20
hard    site01    2011     30    20
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168

1 Answers1

0

You can use ave:

transform(dat, avg = ave(value, type, location))

The result:

  type location year value avg
1 soft   site01 2010    20  15
2 soft   site01 2011    10  15
3 hard   site01 2010    10  20
4 hard   site01 2011    30  20
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168