2
votes

I've got my data frame which looks like 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 with 4 areas and 2 species giving 120 results.

I'd like to add a new column with the relative density for that year in that area/species (as a percentage). I've wrote a small function to get the relative density:

relative <- function(x) (x/sum(x)) * 100

I'm not sure how to get the right set of data to work this out with the group_by and summarise functions. I need to be able to retrieve all the densities for a given year,species,area and rainfall category

any help?

1
The data provided have only one area and every year has only one values, it is hard to provide an example because if you aggregate by year and divide by the sum of year you get always 1.SabDeM
Your question looks like an assignment, maybe it's not. To calculate the relative Sepal.Length of iris flowers in the sample dataset, you could do iris2 <- iris %>% group_by(Species) %>% mutate(rel = Sepal.Length/sum(Sepal.Length)*100)Paul Rougieux
@Paul4forest Thank you! i realised it was a combination of using mutate and the right group by conditions that i neededTom
If you have found an answer, post it, preferably with reproducible code and mark it as accepted.Paul Rougieux

1 Answers

2
votes

In base R it is something like that:

df$sumval <- tapply(df$density, list(df$year, df$area, df$species), sum )
df$perce <- df$density / df$sumval

but as I said in my comment it has always 1 as a result because every year has only one value.