从向量中为data.table的每一行选择一个随机元素 [英] Pick one random element from a vector for each row of a data.table
本文介绍了从向量中为data.table的每一行选择一个随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名称的数据框。和我有一个不同的食物的矢量。我要从该向量中为每个名称随机选择一个元素,以便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)]
项目(向量元素)为大家,而不是不同的随机元素像上述例子。
dt[,NextItem:= sample(x,1)]
but it samples the same food item(vector element) for everyone, not different random elements like aforementioned example.
推荐答案
我们可以使用group by选项,然后执行 sample
p>
We can use group by option and then do sample
dt[, NextItem := sample(x, 1), by = Name]
或者您也可以使用 .N
而不是 / code>
Or you can also do this with .N
instead of by
dt[, NextItem := sample(x, .N, replace = TRUE)]
这篇关于从向量中为data.table的每一行选择一个随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文