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 below.
x<- c("apple","pepsi","rice","coke","banana","butter","bread")
library(data.table)
dt <- fread('
Name NextItem
John rice
Logan butter
Sarah bread
Vinny rice
')
I want the sampling with replacement. I have tried
dt[,NextItem:= sample(x,1)]
but it samples the same food item(vector element) for everyone, not different random elements like aforementioned example.
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)]
来源:https://stackoverflow.com/questions/39334812/pick-one-random-element-from-a-vector-for-each-row-of-a-data-table