Home > front end >  Randomly extract elements in a list which belongs to a list and know the postition
Randomly extract elements in a list which belongs to a list and know the postition

Time:10-24

I have a list consisting of several lists like this:

example_list <- list(c(1,2,3,4),c(1,0,0,0,1),matrix(1:12,3,4),matrix(1:12,4,3))

How can I randomly extract just one element from example_list, and know exactly the position of the element? For example if I picked 1, how could I know this 1 is the first element of the second list and not any others? The return should be the order of the sublist and also the order of the element in the sublist.

Note that, all sublists are formed of numeric, not string or character.

I have searched but still failed to find a suitable solution, can someone help me out? Really appreciate it!

CodePudding user response:

I think this is what you want:

set.seed(99)
sample_list <- function(x) {
  i <- sample(length(x), 1)
  list(i, x[[i]])
}

sample_list(example_list)

Gives:

[[1]]
[1] 4

[[2]]
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

CodePudding user response:

We may name the list with the sequence of list and use sample

names(example_list) <- seq_along(example_list)
example_list[sample(seq_along(example_list), 1)]
$`4`
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12
  •  Tags:  
  • r
  • Related