Search code examples
rlistbin

R : How to assign data points to a bin as a list ? Getting error- zero replacement length and warning - not a multiple of replacememt length


Please help me in figuring out what is going wrong in the following code.

library(rlist)
table<-list()
bin_indices<-c(3,3,1,3,3,2,3,1,1,3)
data_indices<-c(1,2,3,4,5,6,7,8,9,10)

for(data_index in seq_along(bin_indices)){
        bin_index<-bin_indices[data_index]

        if(!(bin_index%in%table)){
        #If no list yet exists,assign the bin an empty list.
                table[bin_index]<-list()

        }

       table[bin_index]<-list.append(table[bin_index],data_index) 

        } 

When I run the above code I get the following error

   Error in table[bin_index] <- list() : replacement has length zero
   In addition: Warning message:
   In table[bin_index] <- list.append(table[bin_index], data_index) :
   number of items to replace is not a multiple of replacement length 

Basically I am trying to assign the data_indices to the corresponding bin indices. There are 3 different bin_indices namely 1,2 and 3 and 10 data indices having values 1 to 10. As an end result I want

data indices 3,8,9 assigned to table[1] as a list
data indices 6     assigned to table[2] as a list
data indices 1,2,4,5,7,10 assigned to table[3] as a list

Thanks


Solution

  • I would use this code to accomplish what I think you want:

    bin_indices<-c(3,3,1,3,3,2,3,1,1,3)
    data_indices<-c(1,2,3,4,5,6,7,8,9,10)
    
    lapply(sort(unique(bin_indices)), function(x) data_indices[which(bin_indices==x)])
    #> [[1]]
    #> [1] 3 8 9
    #> 
    #> [[2]]
    #> [1] 6
    #> 
    #> [[3]]
    #> [1]  1  2  4  5  7 10
    

    Although possibly you want a list of lists, and not a list of vectors. If you want a list of lists use as.list(data_indices[which(bin_indices==x)]) inside this code.

    The problem with your code is essentially that you are thinking in some other language and trying to literally translate into R. It is hard to know where to start with suggestions. The crux of the problem is a misunderstanding of what %in% does.

    Run this code and study and understand the results:

    foo <- list(1:2, 1:4)
    bar <- list(1:2)
    baz <- 1:2
    qux <- 1
    
    qux %in% baz
    qux %in% bar
    qux %in% foo
    baz %in% bar
    baz %in% foo
    bar %in% foo
    foo %in% foo
    

    In my opinion it's unusual to use %in% with lists. It's mainly used with atomic vectors (i.e. vectors of constants like c(1,2,3) or c("a","b",c")).