rj-nirbhay
rj-nirbhay

Reputation: 679

Challenge Replacing Soft-deprecated funs_() within mutate_at

I had written a function that creates lag transformation for variables in data frame. Now as dplyr has soft depreciated funs_ argument, it's giving me warning to use list in place of funs_. below given is my lag transformation function which is working fine but I want to modify it using updated argument list.

lagTransformation<- function(ds,n)
{
  # this function creats lag transformation of dataframe
  # args:
  # ds : Dataset
  # n : number of lags

  require(dplyr)
  lags <- seq(n)
  lag_names <- paste("lag", formatC(lags, width = nchar(max(lags)), flag = "0"), sep = "")
  lag_functions <- setNames(paste("dplyr::lag(., ", lags, ")"), lag_names)
  ds <-ds %>% mutate_at(vars(names(ds)), funs_(lag_functions)) %>% select(contains("_lag"))
  return(ds)
}

Tried replacing funs_ with list but got an error

lagTransformation<- function(ds,n)
{
  # this function creats lag transformation of dataframe
  # args:
  # ds : Dataset
  # n : number of lags

  require(dplyr)
  lags <- seq(n)
  lag_names <- paste("lag", formatC(lags, width = nchar(max(lags)), flag = "0"), sep = "")
  lag_functions <- setNames(paste("dplyr::lag(., ", lags, ")"), lag_names)
  ds <-ds %>% mutate_at(vars(names(ds)), list(~.lag_functions)) %>% select(contains("_lag"))
  return(ds)
}

Error in get(.x, .env, mode = "function") : object 'dplyr::lag(., 1 )' of mode 'function' was not found

referred below question but not able to rectify the error

Create new variables with mutate_at while keeping the original ones

what modification I need?

Upvotes: 2

Views: 113

Answers (1)

stefan
stefan

Reputation: 123978

Using purrr::map to set up the list of lag_functions this can be achieved like so

library(dplyr)
library(purrr)

lagTransformation<- function(ds,n)
{
  # this function creats lag transformation of dataframe
  # args:
  # ds : Dataset
  # n : number of lags

  require(dplyr)
  lags <- seq(n)
  lag_names <- paste("lag", formatC(lags, width = nchar(max(lags)), flag = "0"), sep = "")
  lag_functions <- purrr::map(lags, ~ function(x) dplyr::lag(x, .x)) %>% 
    setNames(lag_names)
  ds <- ds %>% mutate_at(vars(names(ds)), lag_functions) %>% select(contains("_lag"))
  return(ds)
}

lagTransformation(mtcars[1:4], 2) %>% head()
#>   mpg_lag1 cyl_lag1 disp_lag1 hp_lag1 mpg_lag2 cyl_lag2 disp_lag2 hp_lag2
#> 1       NA       NA        NA      NA       NA       NA        NA      NA
#> 2     21.0        6       160     110       NA       NA        NA      NA
#> 3     21.0        6       160     110     21.0        6       160     110
#> 4     22.8        4       108      93     21.0        6       160     110
#> 5     21.4        6       258     110     22.8        4       108      93
#> 6     18.7        8       360     175     21.4        6       258     110

Created on 2020-04-25 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions