Konrad Rudolph
2023-Aug-27 14:59 UTC
[Rd] Calling a replacement function in a custom environment
Hello all, I am wondering whether it?s at all possible to call a replacement function in a custom environment. From my experiments this appears not to be the case, and I am wondering whether that restriction is intentional. To wit, the following works: x = 1 base::is.na(x) = TRUE However, the following fails: x = 1 b = baseenv() b$is.na(x) = TRUE The error message is "invalid function in complex assignment". Grepping the R code for this error message reveals that this behaviour seems to be hard-coded in function `applydefine` in src/main/eval.c: the function explicitly checks for `::` and :::` and permits those assignments, but has no equivalent treatment for `$`. Am I overlooking something to make this work? And if not ? unless there?s a concrete reason against it, could it be considered to add support for this syntax, i.e. for calling a replacement function by `$`-subsetting the defining environment, as shown above? Cheers, Konrad -- Konrad Rudolph // @klmr [[alternative HTML version deleted]]
Duncan Murdoch
2023-Aug-27 16:02 UTC
[Rd] Calling a replacement function in a custom environment
I think there isn't a way to make this work other than calling `is.na<-` explicitly: x <- b$`is.na<-`(x, TRUE) It seems like a reasonable suggestion to make b$is.na(x) <- TRUE work as long as b is an environment. If you wanted it to work when b was a list, it would be more problematic because of partial name matching. E.g. suppose b was a list containing functions partial(), partial<-(), and part<-(), and I call b$part(x) <- 1 what would be called? Duncan Murdoch On 27/08/2023 10:59 a.m., Konrad Rudolph wrote:> Hello all, > > I am wondering whether it?s at all possible to call a replacement function > in a custom environment. From my experiments this appears not to be the > case, and I am wondering whether that restriction is intentional. > > To wit, the following works: > > x = 1 > base::is.na(x) = TRUE > > However, the following fails: > > x = 1 > b = baseenv() > b$is.na(x) = TRUE > > The error message is "invalid function in complex assignment". Grepping the > R code for this error message reveals that this behaviour seems to be > hard-coded in function `applydefine` in src/main/eval.c: the function > explicitly checks for `::` and :::` and permits those assignments, but has > no equivalent treatment for `$`. > > Am I overlooking something to make this work? And if not ? unless there?s a > concrete reason against it, could it be considered to add support for this > syntax, i.e. for calling a replacement function by `$`-subsetting the > defining environment, as shown above? > > Cheers, > Konrad >