This may be basic, but I've been trying to figure it out for days and haven't found an answer.
I am trying to calculate a new quantity based on two columns 'concentration' and 'area' grouped by 'catchment'. I've written a function to calculate the difference in concentration for each row and the row with the largest area normalized by proportion of area in that catchment, but it won't work with dplyr
or aggregate
(. It works fine with by, but then returns a list.
Ideally, I want to add a column onto the dataframe or replace the concentration column altogether. Here is the dataframe 'lev':
area catchment concentration
1 1 Yup 2.00000
2 10 Yup 40.50000
3 25 Yup 50.82031
4 35 Yup 50.00000
5 1 Nope 1.00000
6 10 Nope 5.00000
7 25 Nope 40.08333
8 35 Nope 38.00000
Here is the function:
lever <- function(data=lev, x=data[,"concentration"], y=data[,"area"]){
N= which.max(y)
L = (x - x[N]) * y/max(y)
return(L)}
And here is the desired result:
area catchment concentration leverage
1 1 Yup 2.00000 -1.3714286
2 10 Yup 40.50000 -2.7142857
3 25 Yup 50.82031 0.5859375
4 35 Yup 50.00000 0.0000000
5 1 Nope 1.00000 -1.0571429
6 10 Nope 5.00000 -9.4285714
7 25 Nope 40.08333 1.4880952
8 35 Nope 38.00000 0.0000000
Using by
, I can get two lists with the results for each catchment:
by(lev, lev$catchment, lever)
but I want to use the function on multiple columns categorized by several factors (e.g. date in addition to catchment) and I get
'incorrect number of dimensions'
errors with doBy
and dplyr
.