Search code examples
dplyrtidyversetibble

How to sample elements in a list nested within a tibble?


a = tribble(~i,~k,
            c(1,2,3),2) %>%
  mutate(picks = sample(i,k))

I want to sample k elements within i, but mutate thinks that I want to sample i as singular element.


Solution

  • You were close; just need to add in rowwise and wrap sample in list().

    library(tidyverse)
    
    a = tribble(~i,~k,
                c(1,2,3),2) %>%
      rowwise %>% 
      mutate(picks = list(sample(i,k)))
    
    a
    
    #  i             k picks    
    #  <list>    <dbl> <list>   
    #1 <dbl [3]>     2 <dbl [2]>