Monday, November 30, 2009

R farts: lists

I've been thinking about doing an R idioms post on indexing, but I need to talk about data structures to do that first... and I just can't get it together yet, so here's an R fart:

### Start with a list
aList <- list()

### Lists in R can hold vectors, of _unrelated_ types, with names 
### attached.  The list we made above is empty, and R will tell you 
### so if you ask:
print(aList)
str(aList)

### Once a list is created, we can add named objects to it like so:
aList[['bob']] <- 3
aList$frank <- 'five'
aList['3'] <- 'ten'
aList['4'] <- list(5)

### Each of these is neatly slotted in after the other and, as 
### expected, the list then has a length of four:
length(aList)

### The names of the objects can be extracted
names(aList)

### Either names or numbers can be used for indexing,
### then each element of the list is printed in turn:
for ( i in names(aList) ) {
  print( aList[[i]] )
}

for ( i in seq_along(aList) ) {
  print( aList[[i]] )
}

### Weirdness!
### If you index with single brackets, you get the 
### elements of the list, each as a list of length 1.  
### There's a reason this happens
for ( i in names(aList) ) {
  print( aList[i] )
}


### You can add unnamed objects like so:
aList[[10]] <- 8

### Something funny happened:
print(aList)

### When elements are added to a list by numerical index, and 
### the intervening elements between 1 and N do not exist, 
### the intervening elements are filled with unnamed NULLs.

### Now something funny happens:
aList[['5']] <- list(5)

### To actually get at that unnamed five as a length 1 numeric 
### vector you have to say:
print(aList[['5']][[1]])

### What's the use?  We'll do that next.


No comments:

Post a Comment