[R] types of vectors / lists

Charilaos Skiadas cskiadas at gmail.com
Wed Mar 5 21:54:00 CET 2008


On Mar 5, 2008, at 2:56 PM, a9804814 at unet.univie.ac.at wrote:

> Hello,
>
> I am an advanced user of R. Recently I found out that apparently I do
> not fully understand vectors and lists fully
> Take this code snippet:
>
>
> T = c("02.03.2008 12:23", "03.03.2008 05:54")
> Times = strptime(T, "%d.%m.%Y %H:%M")
> Times                 # OK

Far from OK, which is where your misunderstanding starts. Times is a  
POSIXlt object, and behaves as such, not as a vector and not as a  
list. Rather, a bit of both.
The output you see is the result of print(Times), which calls  
print.POSIXlt(Times), which is:

function (x, ...)
{
     print(format(x, usetz = TRUE), ...)
     invisible(x)
}
<environment: namespace:base>


This in turn calls format.POSIXlt(Times), which is pretty complicated  
and I'll omit here, but point is what you see when you type Times is  
not the object TImes itself, but only what the writer of  
print.POSIXlt wants you to see. Similar to the output of lm, which is  
much less than what lm really contains.

Have a look at ?POSIXlt, which says:

Class "POSIXlt" is a named list of vectors representing .... 9  
vectors following.

Try:

names(Times)
Times$sec
Times$min
....

Now perhaps this helps understand the answers?

> class(Times)          # OK
> is.list(Times)        # sort of understand and not understand that
> length(Times)         # 9 ??? why is it length(Times[1]) ??
>
> Times[1] # OK

Not OK at all. This calls [.POSIXlt, look at:

`[.POSIXlt`

In particular, try Times[2], Times[3] etc

Times[[1]] is the same as Times$sec
Times[[2]] is the same as Times$min
and so on.


> Times[[1]] # Wrong
>
>
> so Times is a vector-style thing of a non-atomic type.
> What puzzles me is first that is.list returns true, and more  
> importantly
> that the length-query returns the length of the first object of that
> apparent list and not how many elements are contained (i.e., I would
> have expected 2 as result - and I do not know what syntax to use in
> order to get the 2).
>
> Moreover, if the whole thing is part of a data.frame:
>
> DFTimes = as.data.frame(Times)
> dim(DFTimes)
> length(DFTimes$Times)  # OK, 2
>
> then everything is as expected.
>
> Could anyone please clearify why is.list returns true and why  
> length in
> the first example returns 9 ? Is it that c() makes a list if the  
> objects
> to be concatenated are not representable directly by atomic types ?
>
> thanks,
> Thomas
>

Haris Skiadas
Department of Mathematics and Computer Science
Hanover College



More information about the R-help mailing list