tags:

views:

49

answers:

1

I'm trying to create an empty list which will have as many elements as there are num.of.walkers. I then try to append, to each created element, a new sub-list (length of new sub-list corresponds to a value in a.

When I fiddle around in R everything goes smooth:

list.of.dist[[1]] <- vector("list", a[1])
list.of.dist[[2]] <- vector("list", a[2])
list.of.dist[[3]] <- vector("list", a[3])
list.of.dist[[4]] <- vector("list", a[4])

I then try to write a function. Here is my feeble attempt that results in an error. Can someone chip in what am I doing wrong?

countNumberOfWalks <- function(walk.df) {
    list.of.walkers <- sort(unique(walk.df$label))
    num.of.walkers <- length(unique(walk.df$label))

    #Pre-allocate objects for further manipulation
    list.of.dist <- vector("list", num.of.walkers)
    a <- c()

    # Count the number of walks per walker.
    for (i in list.of.walkers) {
        a[i] <- nrow(walk.df[walk.df$label == i,])
    }
    a <- as.vector(a)

    # Add a sublist (length = number of walks) for each walker.
    for (i in i:num.of.walkers) {
        list.of.dist[[i]] <- vector("list", a[i])
    }
    return(list.of.dist)
}

> num.of.walks.per.walker <- countNumberOfWalks(walk.df)
Error in vector("list", a[i]) : vector size cannot be NA
+1  A: 

Assuming 'walk.df' is something like:

walk.df <- data.frame(label=sample(1:10,100,T),var2=1:100)

then:

countNumberOfWalks <- function(walk.df) {
    list.of.walkers <- sort(unique(walk.df$label))
    num.of.walkers <- length(unique(walk.df$label))

    list.of.dist <- vector("list", num.of.walkers)

    for (i in 1:num.of.walkers) {
        list.of.dist[[i]] <- vector("list", 
        nrow(walk.df[walk.df$label == list.of.walkers[i],]))}

    return(list.of.dist)
}

Will achieve what you're after.

wkmor1
Use of length() in the for() loop should be replaced with nrow(), but other than that - perfect!
Roman Luštrik
I'm curious why my solution didn't work, does anyone know?To answer your question regarding the soundness of creating a list of lists - I want to pre-allocate an empty list which will be used to accommodate RasterLayer objects. I think this is a bit more elegant than creating objects with deparse().
Roman Luštrik
@romunov. Ok fair enough.
wkmor1
Short answer as to why your original function didn't work: In the first 'for' loop you were trying to assign values to elements of 'a', which wasn't working because 'a' had no elements.
wkmor1