Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
R_inferno.pdf
Скачиваний:
6
Добавлен:
21.05.2015
Размер:
947.8 Кб
Скачать

8.1. GHOSTS

CIRCLE 8. BELIEVING IT DOES AS INTENDED

8.1.68capitalization

Some people have a hard time with the fact that R is case-sensitive. Being casesensitive is a good thing. The case of letters REALLy doEs MakE a diFFerencE.

8.1.69scoping

Scoping problems are uncommon in R because R uses scoping rules that are intuitive in almost all cases. An issue with scoping is most likely to arise when moving S+ code into R.

Perhaps you want to know what \scoping" means. In the evaluator if at some point an object of a certain name, z say, is needed, then we need to know where to look for z. Scoping is the set of rules of where to look.

Here is a small example:

>z <- 'global'

>myTopFun function () f

subfun <- function() f

paste('used:', z)

g

z <- 'inside myTopFun' subfun()

g

> myTopFun()

[1] "used: inside myTopFun"

The z that is used is the one inside the function. Let's think a bit about what is not happening. At the point in time that subfun is de ned, the only z about is the one in the global environment. When the object is assigned is not important. Where the object is assigned is important. Also important is the state of the relevant environments when the function is evaluated.

8.1.70scoping (encore)

The most likely place to nd a scoping problem is with the modeling functions. Let's explore with some examples.

> scope1 function () f

sub1 <- function(form) coef(lm(form))

xx<- rnorm(12)

yy<- rnorm(12, xx) form1 <- yy ~ xx sub1(form1)

g

> scope1()

78

8.1. GHOSTS

CIRCLE 8. BELIEVING IT DOES AS INTENDED

(Intercept) xx -0.07609548 1.33319273 > scope2

function () f

sub2 <- function() f form2 <- yy ~ xx coef(lm(form2))

g

xx<- rnorm(12)

yy<- rnorm(12, xx) sub2()

g

> scope2() (Intercept) xx -0.1544372 0.2896239

The scope1 and scope2 functions are sort of doing the same thing. But scope3 is di erent|it is stepping outside of the natural nesting of environments.

>sub3 function () f

form3 <- yy ~ xx coef(lm(form3))

g

>scope3

function () f

xx<- rnorm(12)

yy<- rnorm(12, xx) sub3()

g

> scope3()

Error in eval(expr, envir, enclos) : Object "yy" not found

One lesson here is that the environment of the calling function is not (necessarily) searched. (In technical terms that would be dynamic scope rather than the lexical scope that R uses.)

There are of course solutions to this problem. scope4 solves the problem by saying where to look for the data to which the formula refers.

> sub4

function (data) f form4 <- yy ~ xx

coef(lm(form4, data=data))

g

> scope4 function () f

xx <- rnorm(12)

79

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]