error in using primitive function subsetting and assignment

Hi, Guys, I'm learning Advanced R book, when I looked into Evaluation Chapter, I wanna test to create my own transform function, but I encountered problem when using primitive subsetting and assignment function [[<-

rm(list = ls())
df <- mtcars
`[[<-`(df, 'mpg', value = rlang::eval_tidy(expr(-mpg), data = df))
df %>% pull(mpg)

I believe that I will get a negative mpg column, but after subsetting and assignment, I couldn't get what I want

Evaluating an expression does not preserve it; it must be assigned to a name.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(rlang)
# reprex should be cut-and-paste, so don't erase anything in the user's 
# environment--let the user decide
# rm(list = ls())
# don't use df, data or any other built-in function name
dat <- mtcars

# assign the expression to some name
DAT <- `[[<-`(dat, 'mpg', value = eval_tidy(expr(-mpg), data = dat))

DAT %>% dplyr::pull(mpg)
#>  [1] -21.0 -21.0 -22.8 -21.4 -18.7 -18.1 -14.3 -24.4 -22.8 -19.2 -17.8 -16.4
#> [13] -17.3 -15.2 -10.4 -10.4 -14.7 -32.4 -30.4 -33.9 -21.5 -15.5 -15.2 -13.3
#> [25] -19.2 -27.3 -26.0 -30.4 -15.8 -19.7 -15.0 -21.4

# or just
DAT$mpg
#>  [1] -21.0 -21.0 -22.8 -21.4 -18.7 -18.1 -14.3 -24.4 -22.8 -19.2 -17.8 -16.4
#> [13] -17.3 -15.2 -10.4 -10.4 -14.7 -32.4 -30.4 -33.9 -21.5 -15.5 -15.2 -13.3
#> [25] -19.2 -27.3 -26.0 -30.4 -15.8 -19.7 -15.0 -21.4
1 Like

Hi, thanks a lot, and I can use assign function to do assignment

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.