[R] custom function insite dlys::mutate

SIMON Nicolas N|co|@@@SIMON @end|ng |rom @p-hm@|r
Mon Mar 30 15:21:45 CEST 2020


Hi,

I tried to use mutate from dplyr with a personal function to create a new variable of a data.frame.

All examples I found are such as myfunction(x){...}.

In my script, the function calls:
- one variable coming from the data.frame
- variables coming from lists or constant outside the data.frame

My function is something like:

var1 <- seq(0,20,1)
dat <- data.frame(var1)
var2 <- c(0,2,4,8)
var3 <- 44.44
var4 <- 0.5

Myfunction <- function(var1, var2, var3,var4){
   obs <- 0
   obs1 <- 0
   for (i in 1:length(var2)) {
         tt <- var2[i]
         if ( var1 > tt ){
             obs1 <- var3 * exp(-var4*var1)
         }
         else obs1 <- 0.0
         obs <- obs + obs1
   }
  return(obs)
}
dat2 <- mutate(dat, obs = Myfunction(var1=var1,var2=var2,var3=var3))

Apparently the condition " if ( var1 > tt ) " cannot be evaluated correcty.

Could you please give me an advice to write it properly?



Best regards
Nicolas


	[[alternative HTML version deleted]]



More information about the R-help mailing list