Roman Luštrik
Roman Luštrik

Reputation: 70653

trying to append a list, but something breaks

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

Upvotes: 0

Views: 500

Answers (1)

wkmor1
wkmor1

Reputation: 7426

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.

Upvotes: 2

Related Questions