JeffreyRacine / R-Package-np

R package np (Nonparametric Kernel Smoothing Methods for Mixed Data Types)
https://socialsciences.mcmaster.ca/people/racinej
47 stars 18 forks source link

npcdenbw (0.60-2) does not formulas which require evaluation in parent environment #8

Closed ScottAThompson closed 6 years ago

ScottAThompson commented 9 years ago

I encountered some unexpected behaviour in the form of an error from a change to one of the examples. I replaced the formula in the function with a formula made from a string. The function npcdensbw function (the formula variant) appears to have problems with this.

The behaviour can be replicated with this code:

library(np)

ds = data.frame(V1=runif(n=100))
ds$y = as.factor(ds$V1 > .5)

f = formula("y~V1")
bws = npcdensbw(f, data=ds) # errors

The npcdensbw call produced an error:

Error in names(res) <- c("response", "terms") : 'names' attribute [2] must be the same length as the vector [1]

A trace back on the error and some digging found the function explodeFormula is receiving the unevaluated formula. Looking at the code for npcdensbw, there is an eval of mf to the parent environment but it occurs after the output of explodeFormula is processed.

I am not sure if I have understood all the cases you are handling but the following code appears to resolve the issue when inserted just before the explodeFormula call:

if (m[2] > 0) { # use data as environment
  mf[["formula"]] = eval(mf[[m[1]]], environment(mf[[m[2]]]))
} else { # use parent frame
  mf[["formula"]] = eval(mf[[m[1]]], parent.frame())
}

Similar code occurs in the npcdistbw function and demonstrates the same behaviour. I have not checked the code I used there but expect it would also resolve that issue.

mjuraska commented 6 years ago

Dear Jeff, Is it possible to implement the above suggested fix for the issue in 'npcdensbw' with formulas as illustrated above? Many thanks, Michal

JeffreyRacine commented 6 years ago

Apologies for neglecting this (and other) open issues, hopefully resolved. Thanks!