Pick one random element from a vector for each row of a data.table

后端 未结 1 1796
独厮守ぢ
独厮守ぢ 2021-01-21 15:19

I have a dataframe of names. And I have a vector of different food items. I want to pick one element from that vector randomly for each Name so that the data.table looks like be

相关标签:
1条回答
  • 2021-01-21 16:08

    We can use group by option and then do sample

    dt[, NextItem := sample(x, 1), by = Name]
    

    Or you can also do this with .N instead of by

    dt[, NextItem := sample(x, .N, replace = TRUE)]
    
    0 讨论(0)
提交回复
热议问题