0

i ve a data frame in R with variables and want to compute a new variable D.

variable A has ID for an area, variable B has different species (1,2,3, etc.), variable C has different values and i want now compute a new variable where D= mean of variable C of species 1 (variable B) in area 1 (variable A) and so on, for every different species in evry plot i need such a new value.

i hope you can understand my problem

burton030
  • 405
  • 4
  • 8
  • 23

1 Answers1

1

I think this should do the trick:

df$D <- ave(df$C, list(df$A, df$B))

If you wish to ignore NA values in df$c, you have to modify the above as follows:

df$D <- ave(df$C, list(df$A, df$B), FUN = function (x) mean(x, na.rm=T))
Tamás
  • 47,239
  • 12
  • 105
  • 124