Search code examples
rlistvectorsamplesampling

Sampling an element from a list in R


I have a list called MyList that looks like this:

[[1]]
[1] 5

[[2]]
integer(0)

[[3]]
[1]  5 16

[[4]]
[1] 9

[[5]]
integer(0)

I want to sample one of the numbers 5,5,16,9 along with which list element it has come from. E.g. if the first 5 is picked out I would like the sample result to be c(1,5) but if the second 5 is chosen I want the result to be c(3,5). I also don't want to include empty values integer(0) in the sampling.


Solution

  • One way would be to bring this list in a more manageable data structure (like matrix or a dataframe) dropping the empty values.

    mat <- unname(do.call(rbind, Map(function(x, y) 
                   if(length(y)) cbind(x, y), seq_along(MyList), MyList)))
    mat
    #      [,1] [,2]
    #[1,]    1    5
    #[2,]    3    5
    #[3,]    3   16
    #[4,]    4    9
    

    then select any one row from the matrix.

    mat[sample(nrow(mat), 1),] 
    

    data

    MyList <- list(5, integer(0), c(5, 16), 9, integer(0))