0

The dataframes I work with have an arbitrary number of variables, and are of arbitrary length. I'd like to create a function to normalize each column by its earliest value. I'm new to R/tidyverse, and thought a for loop would work:

 Col.norm <- function(df){
             for (i in c(2:ncol(df))) {
             select(df,i) %>%
             mutate(df[]/df[[1]])
             }}  

A representative df with a date column and 3 variables looks like this:

Z <- data.frame(date = seq(as.Date("2018-06-01"), as.Date("2018-06-11"),   "days"), A = c(5:15), B = c(6:16), C= c(7:17))  

Running the above function on that df gives the following error:

"Error in mutate_impl(.data, dots) : Evaluation error: non-numeric argument to binary operator"

Any help would be greatly appreciated - not sure how to loop after doing the select step...I've spent a ton of time on this...

pogibas
  • 27,303
  • 19
  • 84
  • 117
Tom.K
  • 1
  • 2

1 Answers1

0
Col.norm <- function(df) {
  mutate_at(df, -1, funs(. / head(., 1)))
}
Jonathan Gilligan
  • 701
  • 1
  • 5
  • 21