Reputation: 3099
I have a list of lists called my_list_of_lists
, from which I want to select a certain number of elements.
my_list_of_lists
, I want to select 1 element at randommy_list_of_lists
, I want to select 1 element at randommy_list_of_lists
, I want to select 2 elements at randomHere 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?
Upvotes: 1
Views: 1478
Reputation: 15072
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).
Upvotes: 1
Reputation: 206207
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
.
Upvotes: 3