WinVector / wrapr

Wrap R for Sweet R Code
https://winvector.github.io/wrapr/
Other
136 stars 11 forks source link

Unexpected Behaviour with Aliased List Variables #3

Closed jpryda closed 6 years ago

jpryda commented 6 years ago

There seems to be inconsistency in referencing named items in a list passed in as a parameter:

params.list <- list(
  MQT_TBL_1_ = 'dir_p_pts',
  MQT_AGG_TYPE_ = 'max'
)

applyAgg <- function(params.list.agg){
  wrapr::let(
    alias=list(MQT_TBL_1_=params.list.agg$MQT_TBL_1_),
    expr={
      print(params.list.agg$MQT_TBL_1_)         # This doesn't work (aliased)
      print(params.list.agg[["MQT_TBL_1_"]])   # This does work     (aliased)

      print(params.list.agg$MQT_AGG_TYPE_)       # This does work (not aliased)     
      print(params.list.agg[["MQT_AGG_TYPE_"]]) # This does work (not aliased)
    })
}

applyAgg(params.list)
JohnMount commented 6 years ago

Actually wrapr is working as intended on the example. Probably not doing what you want, but you may be able to work into it if you are interested.

Here is your example with debugging turned on.

reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-13

library("wrapr")
packageVersion("wrapr")
#> [1] '1.0.1'

params.list <- list(
  MQT_TBL_1_ = 'dir_p_pts',
  MQT_AGG_TYPE_ = 'max'
)

applyAgg <- function(params.list.agg){
  wrapr::let(
    alias=list(MQT_TBL_1_=params.list.agg$MQT_TBL_1_),
    expr={
      print(params.list.agg$MQT_TBL_1_)         # This doesn't work (aliased)
      print(params.list.agg[["MQT_TBL_1_"]])   # This does work     (aliased)

      print(params.list.agg$MQT_AGG_TYPE_)       # This does work (not aliased)     
      print(params.list.agg[["MQT_AGG_TYPE_"]]) # This does work (not aliased)
    },
    debugPrint = TRUE)
}

applyAgg(params.list)
#> $MQT_TBL_1_
#> [1] "dir_p_pts"
#> 
#> {
#>     print(params.list.agg$dir_p_pts)
#>     print(params.list.agg[["MQT_TBL_1_"]])
#>     print(params.list.agg$MQT_AGG_TYPE_)
#>     print(params.list.agg[["MQT_AGG_TYPE_"]])
#> }
#> NULL
#> [1] "dir_p_pts"
#> [1] "max"
#> [1] "max"

I've modified wrapr's debug mode to print the alias map in addition to the substituted expression.

wrapr::let() is designed to substitute code symbols (explicit variables and names of columns) for other symbols.

Notice that wrapr::let() only performed a substitution in the first of the four statements.

The rules detailed are:

Some of the intent and rules of wrapr::let() are documented here.

jpryda commented 6 years ago

Thanks a lot for the breakdown John! That makes sense now - no peculiar side effects as I had previously thought.

JohnMount commented 6 years ago

Glad that helped! The substitution stuff can get confusing. Your question gave me the idea of printing more in the debug so one can see what is going on. Like the idea of "breakdown" slowing things down enough so one can see the steps.