如何对嵌套在 tibble 中的列表中的元素进行采样?

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 内的 k 个元素进行采样,但 mutate 认为我想对 i 个元素进行采样。

你很亲密;只需要添加 rowwise 并将 sample 包装在 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]>