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

眉间皱痕 提交于 2019-12-02 05:23:27

问题


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


来源:https://stackoverflow.com/questions/39334812/pick-one-random-element-from-a-vector-for-each-row-of-a-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!