Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 123

Hint – Assignment

Оглавление

Generally it is best to keep it simple, most people will expect to see a left assignment, and while it might make code a little shorter, the right assignment will be a little confusing for most readers. Best is to stick to = or <- and of course <<- whenever assignment in a higher environment is also intended.

In some special cases, such as the definition of parameters of a function, it is not possible to use the “arrow” and onemust revert to the = sign. This makes sense, because that is not the same as a traditional assignment.

mean(v1, na.rm = TRUE) # works (v1 is defined in previous section) ## [1] 1.75+0.375i mean(v1, na.rm <- TRUE) # fails ## Error in mean.default(v1, na.rm <- TRUE): ‘trim’ must be numeric of length one

While the <<- seems to do exactly the same, it changes also the value of the variable in the environment above the actual one. The following example makes clear how <- only changes the value of x while the function is active, but <<- also changes the value of the variable x in the environment where the function was called from.

# f # Assigns in the current and superior environment 10 to x, # then prints it, then makes it 0 only in the function environment # and prints it again. # arguments: # x -- numeric f <- function(x) {x <<- 10; print(x); x <- ; print(x)} x <- 3 x ## [1] 3 # Run the function f(): f(x) ## [1] 10 ## [1] 0 # Only the value assigned with <<- is available now: x ## [1] 10

The Big R-Book

Подняться наверх