Pick one random element from a vector for each row

2020-04-13 16:42发布

问题:

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.

回答1:

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)]