[R] dim vs length for vectors
Uwe Ligges
ligges at statistik.uni-dortmund.de
Fri Jan 21 16:21:47 CET 2005
Olivia Lau wrote:
>>> IMHO the difference between vectors and 1-dimensional arrays is
>>> really annoying and I had already several bugs in my code, because I
>>> mixed these up.
>>> Is it possible in future versions of R that R does not differentiate
>>> between vectors and 1-dimensional arrays (e.g. by treating all
>>> vectors as 1-dimensional arrays)?
>>
>>
>> No, that would break huge amounts of code!
>>
>> See ?"[" and learn how to use its argument "drop".
>
>
> What I was proposing doesn't require a lot of programming. Just
> whenever you call dim(), it does length() if the object is a vector and
> returns it in the format:
>
> R> a <- 1:12
> R> dim(a)
> [1] 12
Dim reports the dimesnion attribute, so why do you want to make it
inconsistant????
> This means that you can provide a unified introduction to data
> structures that take only one type of atomic value (and generally call
> these structures "arrays"). What I call a "one dimensional array" only
> has one dim attribute and hence would use a[4] for extraction (for
> example), which is consistent with the usage for "[" (to my
> understanding). That way, when you introduce "[" and arrays at the same
> time, you can tell beginners:
> 1) Run dim()
> 2) If there's one dim, use [ ]; if there are 2 dims, use [ , ]; if
> there are 3 dims, you use [ , , ].
> This is conceptually easy for a beginner and avoids a bit of frustration.
Well, you forgot that even a matrix is represented as a vector, but with
dimension attributes!
And indexing a matrix vector-like has some benefits in some cases.
> If I need to initiate an empty vector for example I use
>
> R> a <- array()
>
> It just looks like the difference between a 1-d array (which doesn't
> exist as far as I can tell) and a vector is semantic, and I think that R
Note the difference:
x <- 1:5
dim(x) # NULL
str(x) # int [1:5] 1 2 3 4 5
x <- array(1:5, dim=5)
dim(x) # [1] 5
str(x) # int [, 1:5] 1 2 3 4 5
> would be more logical if they were treated as the same thing. This
> doesn't mean changing the way the is.array(), is.vector(), <-, etc
> functions work, but just changing dim().
But then, you won't see the difference beween an 1D array (vector with
dim attribute and a vector without dim attribute any more!
You might want to read the R Language Definition manual.
Uwe Ligges
> Yours,
>
> Olivia Lau
More information about the R-help
mailing list