简体   繁体   中英

Select elements from a list of lists using lapply in R

I have a list of lists called my_list_of_lists , from which I want to select a certain number of elements.

  • from element 1 of my_list_of_lists , I want to select 1 element at random
  • from element 2 of my_list_of_lists , I want to select 1 element at random
  • from element 3 of my_list_of_lists , I want to select 2 elements at random

Here are my_list_of_lists and number_to_select :

my_list_of_lists <- list(
  c(147, 313, 337, 546),
  c(35, 135, 281, 283, 325, 326, 357),
  c(311, 334, 403, 427, 436, 507, 520, 566, 595, 632))

number_to_select <- c(1, 1, 2)

I can do this individually no problem. For example:

sample(my_list_of_lists[[3]],number_to_select[[3]])
#[1] 520 436

But when I try to use lapply , I don't get it:

selected_vals = lapply(my_list_of_lists, function(x) { sample(x, number_to_select)})
selected_vals[[3]]
#[1] 334

How can I use lapply to choose 1 element from the first list, 1 element from the second list, and 2 elements from the third list?

You want to iterate over multiple collections, so you should use Map . For example

Map(sample, my_list_of_lists, number_to_select)

will do what you want by calling sample multiple times with corresponding values of my_list_of_lists and numbers_to_select .

Here is a corresponding solution with purrr::map2 from the tidyverse . You can't use lapply here because you want to map over two objects simultaneously. In general, it's helpful to provide your input in a reproducible format rather than just the head() .

library(tidyverse)
my_list_of_lists <- list(
  c(147, 313, 337, 546),
  c(35, 135, 281, 283, 325, 326, 357),
  c(311, 334, 403, 427, 436, 507, 520, 566, 595, 632)
)

number_to_select <- c(1, 1, 2)

selected_vals <- map2(
  .x = my_list_of_lists,
  .y = number_to_select,
  .f = function(x,y) base::sample(x, y)
  )
print(selected_vals)
#> [[1]]
#> [1] 546
#> 
#> [[2]]
#> [1] 283
#> 
#> [[3]]
#> [1] 507 311

Created on 2018-03-14 by the reprex package (v0.2.0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM