gibbz00 gibbz00 - 2 months ago 7
R Question

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

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.

Answer

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