On 24-Oct-10 19:55:12, ivo welch wrote:> quick programming question. I am not making enough errors in my
> programs, so I want to trigger a few more. ;-)
>
> [1] undefined variable behavior:
>
>> d=data.frame( x=rnorm(1:10), y=rnorm(1:10))
>> z
> Error: object 'z' not found
>> d$z NULL
>
> is this consistent? I thought that z is the same as .GlobalEnv$z,
> but apparently it is not. something here is smart enough to trigger
> an error. I like this error behavior. is it possible to set an R
> global option that triggers the same 'not found' error when an
> undefined element of a list or data frame is accessed?
>
> [just trying to check all my function arguments, and right now,
> I think I need to include for each argument
> 'stopifnot(is.null(argument))'. This clutters the code.]
I'm not expert enough to answer your query properly, but I see
it as an example of the somewhat bewildering variety of ways
in which indexing can be represented in R. With your definition:
.GlobalEnv$d
returns exactly the same as if you had entered simply 'd'.
.GlobalEnv$z
returns NULL, while simply 'z' returns "Error: object 'z'
not found"
as you observed.
d$y
returns a vector consisting of the values of y (printed
"horizontally), as also does d[[2]], while
d[2]
returns a column of the values of y.
str(d[2])
# 'data.frame': 10 obs. of 1 variable:
# $ y: num 0.331 0.57 -0.266 -0.694 -0.992 ...
d[[2]]
returns a vector ("horizontal") exactly like d$y.
Now for d$z etc:
d$z
# NULL
d[3]
# Error in `[.data.frame`(d, 3) : undefined columns selected
d[[3]]
Error in .subset2(x, i, exact = exact) : subscript out of bounds
> [2] is it possible to turn off recycling for vector operations? (I
> may have asked this at some point already, but I can't find the
> answer.)
>
>> a=c(2,3)
>> b=c(4,5,6,7)
>> a+b
> [1] 6 8 8 10
>
> when I really want recycling, I would rather do it explicitly with rep.
> regards,
> /iaw
> ----
But, in such a case, what would you intend a+b to mean?
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 24-Oct-10 Time: 21:25:29
------------------------------ XFMail ------------------------------