Message-ID: <49880678.5070201@idi.ntnu.no>
Date: 2009-02-03T08:55:20Z
From: Wacek Kusnierczyk
Subject: Difference between a[[i]] and a[i]
In-Reply-To: <054F7DF4-64F7-411F-A81F-1DC730D521CF@auckland.ac.nz>
Rolf Turner wrote:
>
> On 3/02/2009, at 12:45 PM, David Epstein wrote:
>
>>
>> I'm sure I've read about the difference between a[[i]] and a[i] in R,
>> but I
>> cannot recall what I read. Even more disturbing is the fact that I don't
>> know how to search the newsgroup for this. All the different
>> combinations I
>> tried were declared not to be valid search syntax.
>
> Essentially: a is a list; a[i] is a list of length 1 whose sole entry is
> the i-th entry of a; a[[i]]] is the i-th entry of a. If you are of a
> mathematical bent it may be illuminating to think of this as being
> analogous
> to, say, {3} being a subset of the set {1,2,3,4,5} and 3 being an element
> of this set.
>
>> 1. What sort of object can the operators [] and [[]] be applied to?
>> How do
>> they differ? I mean objects in standard R, not in packages that provide
>> conceivable overloading of these operators (if that's possible).
>
> Essentially lists. Note that any vector can be considered to be a list.
what do you mean by 'can be considered to be a list'? by whom? not by
the r interpreter, it seems:
v = 1:10
# a vector
l = as.list(1:10)
# a list
is.list(v)
# no
is.list(l)
# yes
is(v, "list")
# no
is(l, "list")
# yes
is(v)
# "integer" "vector" "numeric" "data.frameRowLabels"
is(l)
# "list" "vector"
d = data.frame(x=1:10)
aggregate(d, by=v)
# error: 'by' must be a list
aggregate(d, by=l)
# fine
sort(l)
# error: have you called 'sort' on a list?
sort(v)
# fine, no error
# and the best of all
sort.list(l)
# error: have you called 'sort' on a list?
sort.list(v)
# fine, no error
perhaps you'd care to explain what 'can be considered to be a list' is
supposed to mean precisely, or else you're messing things up.
vQ