2

Questions like R variable names in loop, get, etc are common among people coming to R from other languages. The standard answer is usually, as I gave in that example, that it's not possible to iterate through a list of variables in the global environment and modify the underlying variable, only a copy. This fits in with the R semantics of not passing values by reference and creating copies of objects as necessary.

However, this type of construct works:

xData <- data.frame(a = 1:2, b = 3:4)
yData <- data.frame(a = 4:5, b = 6:7)

varList <- ls(pattern = "Data$")

for(var in varList) {
  .GlobalEnv[[var]]$c <- with(.GlobalEnv[[var]], a + b)
}
xData
#   a b c
# 1 1 3 4
# 2 2 4 6

Other than being poor programming style, and not really fitting with the 'R' way of doing things, are there any specific issues with this style of coding?

Please note I'm not advocating this as a good practice, just curious as to whether this is likely to have unintended side effects.

Community
  • 1
  • 1
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
  • Note if it's felt this question is unhelpful (since it might direct people towards programming practices that are best avoided), I'm happy to delete. – Nick Kennedy Jun 30 '15 at 14:31
  • I propose such usage to be adopted as a standard for future R code. – Vlo Jun 30 '15 at 14:59
  • Interesting question. My guess: It's too much trouble to treat `.GlobalEnv` differently from other lists/environments (for which `[[<-` & `$<-` work) and doesn't match the design philosophy. `pi` and `mean` can be modified, too; and even `"+" <- function(x,y) "-"(x,y); 5+4 # 1` works. This puts more responsibility on the user to avoid crazy/dangerous constructs than is standard in commercial stats software, where everything important is bolted down. – Frank Jun 30 '15 at 15:02
  • @Frank yes, although none of the examples you've given are in `.GlobalEnv`, so `.GlobalEnv[["+"]]` returns NULL (unless you've specifically redefined it of course). – Nick Kennedy Jun 30 '15 at 15:05
  • Sure, your example is adequate illustration of how `.GlobalEnv` can be (ab)used. I'm just saying it looks like part of a broader pattern (that I like) of not bolting things down for user safety. (In Stata, for example, I cannot define a `union` function because the developers might implement one in the future... but haven't done so yet.) – Frank Jun 30 '15 at 15:07

0 Answers0