I am trying to transform variables using a user defined function but facing issues in same.
1. sample dataframe:
librar(tidyverse)
df_test <- tribble(
~sales, ~var1, ~var2,
22, 230.1, 37.8,
10, 44.5, 39.3,
9, 17.2, 45.9,
19, 151.5, 41.3,
13, 180.8, 10.8,
7, 8.7, 48.9,
12, 57.5, 32.8,
13, 120.2, 19.6,
5, 8.6, 2.1,
11, 199.8, 2.6)
df_test
2. Tranformation table
# transfm dataframe
df_transfm <- df_test %>%
select(var1,var2)
df_transfm
3. User defined function to transform variable
# function to transform variables
adstock_transfrm <- function(x, df, adstock_rate = .5){
df %>%
mutate(x = if_else(row_number() == 1, x, x * adstock_rate)) %>%
select(x)
}
4. Apply function
df_transfm$var1 <- adstock_transfrm(x = var1,df = df_transfm)
df_transfm
5. Error
Error in `mutate()`:
! Problem while computing `x = if_else(row_number() == 1, x, x * adstock_rate)`.
Caused by error in `if_else()`:
! object 'var1' not found
Backtrace:
1. global adstock_transfrm(x = var1, df = df_transfm)
9. dplyr::if_else(row_number() == 1, x, x * adstock_rate)
Error in mutate(., x = if_else(row_number() == 1, x, x * adstock_rate)) :
Caused by error in `if_else()`:
! object 'var1' not found
6. function2: changed function & applied but getting tibble instead of values:
# function2 to transform variables
adstock_transfrm2 <- function(x, df, adstock_rate = .5){
x = enquo(x)
df %>%
mutate(!!x := if_else(row_number() == 1, !!x, !!x * adstock_rate)) %>%
select(!!x)
}
df_transfm$var1 <- adstock_transfrm2(x = var1,df = df_transfm)
df_transfm
var1
<tibble>
var2
<dbl>
<tibble> 37.8
<tibble> 39.3
<tibble> 45.9
<tibble> 41.3
<tibble> 10.8
<tibble> 48.9
<tibble> 32.8
<tibble> 19.6
<tibble> 2.1
<tibble> 2.6
Any help is much appreciated.
CodePudding user response:
Try pull()
instead of select
library(dplyr)
df_test <- tribble(
~sales, ~var1, ~var2,
22, 230.1, 37.8,
10, 44.5, 39.3,
9, 17.2, 45.9,
19, 151.5, 41.3,
13, 180.8, 10.8,
7, 8.7, 48.9,
12, 57.5, 32.8,
13, 120.2, 19.6,
5, 8.6, 2.1,
11, 199.8, 2.6)
# transfm dataframe
df_transfm <- df_test %>%
select(var1,var2)
adstock_transfrm2 <- function(x, df, adstock_rate = .5){
x = enquo(x)
df %>%
mutate(!!x := if_else(row_number() == 1, !!x, !!x * adstock_rate)) %>%
pull(!!x)
}
df_transfm$var1 <- adstock_transfrm2(x = var1,df = df_transfm)
df_transfm
#> # A tibble: 10 × 2
#> var1 var2
#> <dbl> <dbl>
#> 1 230. 37.8
#> 2 22.2 39.3
#> 3 8.6 45.9
#> 4 75.8 41.3
#> 5 90.4 10.8
#> 6 4.35 48.9
#> 7 28.8 32.8
#> 8 60.1 19.6
#> 9 4.3 2.1
#> 10 99.9 2.6