I am trying to apply a function to calculate some variables. This is how my output should look like:
In column D, in red, is the way column C should be calculated. This is why I used the function match
. The number to substract (1000) should be the one at the first R occurrence from column A. I never used match
before so maybe there is something wrong here or anywhere else in my function.
This is what I did:
library(dplyr)
p_hi <- 0.472
rate_increase_hi <- 1.058*10^(-3)
seed.mass.fraction.f<-function(stage, p_hi, rate_increase_hi, c_total_biomass, c_biomass_during_rep){
seed.mass.fraction <- 0
if(stage == "V") {rate_increase_hi = 0}
if(stage == "R") {rate_increase_hi = rate_increase_hi}
if(stage == "V") {c_biomass_during_rep = 0}
if(stage == "R") {c_biomass_during_rep = c_total_biomass - c_total_biomass(match("R", stage))}
if(seed.mass.fraction < p_hi) {seed.mass.fraction = rate_increase_hi * c_biomass_during_rep}
if(seed.mass.fraction >= p_hi) {seed.mass.fraction = p_hi}
return(seed.mass.fraction)
}
c_total_biomass <- seq(0, 1600, 100)
stage <- c(rep("V", 10), rep("R", 7))
data.smf<- data.frame(cbind(stage, c_total_biomass)) %>%
mutate(c_total_biomass = as.numeric(c_total_biomass)) %>%
rowwise() %>%
mutate(smf = seed.mass.fraction.f(stage, p_hi, rate_increase_hi, c_total_biomass, c_biomass_during_rep)) %>%
ungroup()
I am getting this error:
Error: Problem with `mutate()` column `smf`.
i `smf = seed.mass.fraction.f(...)`.
x could not find function "c_total_biomass"
i The error occurred in row 11.
CodePudding user response:
The issue is that seed.mass.fraction
is not passed as an input argument and it should be found from the original data, which it couldn't. An option is to use cur_data_all()
to get the data and subset the column
seed.mass.fraction.f<-function(stage, p_hi, rate_increase_hi, c_total_biomass, c_biomass_during_rep){
dat <- cur_data_all()
c_total_biomass <- dat[["c_total_biomass"]]
stage <- dat[["stage"]]
first_c_total_biomass <- dat[["first_c_total_biomass"]]
seed.mass.fraction <- 0
if(stage == "V") {rate_increase_hi = 0}
if(stage == "R") {rate_increase_hi = rate_increase_hi}
if(stage == "V") {c_biomass_during_rep = 0}
if(stage == "R") {c_biomass_during_rep = c_total_biomass - first_c_total_biomass}
if(seed.mass.fraction < p_hi) {seed.mass.fraction = rate_increase_hi * c_biomass_during_rep}
if(seed.mass.fraction >= p_hi) {seed.mass.fraction = p_hi}
return(seed.mass.fraction)
}
-testing
data.frame(stage, c_total_biomass) %>%
mutate(first_c_total_biomass = c_total_biomass[stage == "R"][1]) %>%
rowwise %>%
mutate(smf = seed.mass.fraction.f(stage, p_hi, rate_increase_hi,
c_total_biomass, c_biomass_during_rep)) %>%
ungroup
-output
# A tibble: 17 x 3
stage c_total_biomass smf
<chr> <dbl> <dbl>
1 V 0 0
2 V 100 0
3 V 200 0
4 V 300 0
5 V 400 0
6 V 500 0
7 V 600 0
8 V 700 0
9 V 800 0
10 V 900 0
11 R 1000 0
12 R 1100 0.106
13 R 1200 0.212
14 R 1300 0.317
15 R 1400 0.423
16 R 1500 0.472
17 R 1600 0.472