I'm trying to move data wrangling from excel to R.I have a dataframe (df) with 62 columns and 21 rows. Each of the rows represents a different organisation, and each of the column headings (apart from the first one which gives organisation name) are monthly dates.
The structure looks like this:
structure(list(OrgCode = c("RA", "RB", "RC", "RD"), Provider = c("ORGA", "ORGB", "ORGC", "ORGD"), `Jan-22` = c(0.54, 0.78, 0.715399610136452, 0.37), `Feb-22` = c(0.14, 0.43, 0.65, 0.87)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))
My excel spreadsheet uses the slope() function to take the 3 most recent dates and calculate the slope of them. I want to create a new column in my df in R which contains the slope of the 3 last columns of my df but I can't figure out how to do this.
I've seen some code suggesting taking a linear regression for each provider:
mod <- lm(y ~ x)cf <- coef(mod)Slope <- cf[2]
but I don't know how to save a model (which only uses the last three dates not all the dates available in the dataframe) in a column and then create another column which takes the date of this - seems like there should be a simple function which exists.
Any help greatly appreciated.