Hello- I'm hoping this is a relatively simple question that someone can help me with. I'm trying to calculate growth rate in a small dataset. This is the code I've been trying to work with based on a previous post in RStudio Community. Does anyone happen to know where I'm going wrong?
year <- as.Date(c('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018'),'%Y')
year <- format(as.Date(year, format="%d/%m/%Y"),"%Y")
rate <- c('0','0.3','0.2727','0.325','0.3529412','0.472','0.41666','0.294','0.4285714','0.6285714','0.4','0.5714286')
growth_rate <- data.frame(year,rate)
growth_ = growth_rate %>%
first sort by year
arrange(year) %>%
mutate(Diff_year = year - lag(year), # Difference in time (just in case there are gaps)
Diff_growth = rate - lag(rate), # Difference in route between years
Rate_percent = (Diff_growth / Diff_year)/lag(rate) * 100) # growth rate in percent
This is the error I am getting: Error: Problem with mutate() input Diff_year.
x non-numeric argument to binary operator
i Input Diff_year is year - lag(year).
Hi. Thank you for your reply. I fixed it so year is now a date. But I am still getting an error:
growth_ = growth_rate %>%
> + arrange(year1) %>%
> + mutate(Diff_year = year1 - lag(year1), # Difference in time (just in case there are gaps)
> + Diff_growth = rate - lag(rate), # Difference in route between years
> + Rate_percent = (Diff_growth / Diff_year)/lag(rate) * 100) # growth rate in percent
> Error: Problem with `mutate()` input `Rate_percent`.
> x second argument of / cannot be a "difftime" object
> i Input `Rate_percent` is `(Diff_growth/Diff_year)/lag(rate) * 100`.
> Run `rlang::last_error()` to see where the error occurred.
> > Average_growth = mean(growth_$Rate_percent, na.rm = TRUE)
> Error in mean(growth_$Rate_percent, na.rm = TRUE) :
> object 'growth_' not found
work? Also, I don't know your application, but are you sure you want arithmetic mean instead of geometric mean? And, to be clear, you're trying to calculate the change in the rate, not the rate itself?