[R] custom function insite dlys::mutate

Rasmus Liland jen@r|| @end|ng |rom @tudent@|ko@@u|o@no
Mon Mar 30 21:25:45 CEST 2020


On 2020-03-30 13:21 +0000, SIMON Nicolas wrote:
> Could you please give me an advice to write it 
> properly?

Hi!  To understand what you wanted to do, I tried 
to recreate your example in classic R indexing of 
a data.frame, then converting it to a tibble:

    var1 <- seq(0, 20, 1)
    var2 <- c(0, 2, 4, 8)
    var3 <- 44.44
    var4 <- 0.5
    
    dat <- cbind(var1, var2)
    dat <- as.data.frame(dat)
    idx <- dat$var1 > dat$var2
    dat[idx, "obs1"] <-
      var3 * exp(-var4 * dat[idx, "var1"])
    dat[!idx, "obs1"] <- 0
    dat <- tibble::as_tibble(dat)
    dat

Apparently there is a dplyr::if_else function you 
can use with dplyr::mutate like you wanted to end 
up in the same place:

    var1 <- seq(0, 20, 1)
    var2 <- c(0, 2, 4, 8)
    var3 <- 44.44
    var4 <- 0.5
    
    dat <- cbind(var1, var2)
    dat <- as.data.frame(dat)
    dat <- tibble::as_tibble(dat)
    dat <-
      dplyr::mutate(.data=dat,
        obs=dplyr::if_else(
          var1>var2,
          var3*exp(-var4 * var1),
          0)
      )
    dat

Might this be close to what you were looking to 
do?

/Rasmus



More information about the R-help mailing list