Search code examples
rrowscustom-function

Creating a user defined function that applies an equation to each row


I'm trying to build a function that will apply an equation to each row of a variable and paste the output in another column of a data frame. It's the first bit of my first attempt to build a function and I'm totally stuck. The function creates a couple of columns and then should apply the equation to the columns. So far I've got:

cpeat <- function(data, mo, ko) { 
  data$t1 <- data$t
  data$t2 <- lead(data$t1)
  data$al <- ((mo/ko)*log((1+ko*t2)/(1+ko*t1)))
data.frame("t1" = data$t1, 
           "t2" = data$t2,
           "annual_layer" = data$al)
}

Testing the code returns what I need, but the equation (data$al column) is only applied to the top row and pasted down the column.

I've searched pretty hard and it seems I could just create a function that is solely the equation, and use apply, but this is just the start of what will likely be a end up being a complex function, so I need the columns created properly.

Any help would be massively appreciated, Cheers.


Solution

  • no need to write a function, you are already using dplyr why not use it fully?

    # df is the data.frame you had
    # you have to set mo and ko in the global environment ie mo=.9; ko=0.7
    df %>% mutate(t1=t, t2=lead(t), annual_layer=(mo/ko)*log((1+ko*t2)/(1+ko*t1)))
    

    Edit

    cpeat <- function(data, mo, ko) {
         if(!require(dplyr)){
              install.packages("dplyr")
              library(dplyr)
         }
         data %>% mutate(t1=t, t2=lead(t), annual_layer=(mo/ko)*log((1+ko*t2)/(1+ko*t1))) %>% select(-t)
    }