r - custom functions with dplyr summarise -
i've got data frame looks this:
row year rainfall area species density rainfall1 1 46 1993 433.70 br red 2.9300000 low 2 47 1994 365.65 br red 8.0000000 low 3 48 1996 545.80 br red 5.8558559 high 4 49 1999 785.40 br red 17.0158617 high 5 50 2000 736.30 br red 8.8778409 high 6 51 2001 370.40 br red 6.9874901 low 7 52 2002 174.80 br red 2.0579308 low 8 53 2003 290.50 br red 7.6328655 low 9 54 2004 424.40 br red 7.4234908 low 10 55 2005 336.30 br red 0.7580045 low 11 56 2007 524.40 br red 0.4500000 high
this repeats resulting 4 areas , 2 species giving 120 results.
i'd add new column relative density year in area/species (as percentage). i've wrote small function relative density:
relative <- function(x) (x/sum(x)) * 100
i'm not sure how right set of data work out group_by , summarise functions. need able retrieve densities given year,species,area , rainfall category
any help?
in base r that:
df$sumval <- tapply(df$density, list(df$year, df$area, df$species), sum ) df$perce <- df$density / df$sumval
but said in comment has 1 result because every year has 1 value.
Comments
Post a Comment