I am tracking the body weights of individuals over time, and the function below allow me to calculate the % body weight of the individual on a particular day, relative to the initial value (essentially dividing the body weight on a particular day by the body weight observed on day 1).
variability <- function(df, column_number) {
variable_name <- paste0("var_BW", column_number)
df %>%
mutate(!!variable_name := round(100*(df[,column_number]/df[1,column_number]), 1))
}
This function works fine if I use it on one column, but since I have a number of individuals, I would like to use the apply() family to use the function on multiple columns of one dataframe (for instance on columns 1:8 of the dataframe below):
BW1 BW2 BW3 BW4 BW5 BW6 BW7 BW8
1 18.4 19.6 20.7 17.4 18.7 18.9 19.0 17.8
2 18.1 19.3 20.0 17.5 18.3 19.4 19.5 18.0
3 17.7 18.9 20.4 17.3 18.3 19.2 19.3 17.9
My initial guess is to store the column numbers in a list, and then pass that list as an argument in the lapply() function, as such:
l <- list(1:8)
lapply(working_df, variability, l)
However, when I do that, I get the following error:
Error in UseMethod("mutate_") :
no applicable method for 'mutate_' applied to an object of class "c('double', 'numeric')"
Any thoughts?