lundi 5 septembre 2016

Select one random element from a vector after dynamically excluding certain values

This is my dataframe/data.table that shows what people has already eaten and my target field NextItem which is one next random item(uneaten) that they may eat

library(data.table)
dt <- fread('

            Name  ItemEaten  NextItem
            John   rice       banana
            John   butter     banana
            Sarah  bread      apple
            Vinny  apple      coke
            ')

And this vector x is my universe of food items:

x<- c("apple","pepsi","rice","coke","banana","butter","bread")

The NextItem field should only include food items from the x vector that is not already eaten by the given individual(not in ItemEaten Field). For example, John has already eaten rice & butter,thats why John should have one of the five remaining food items in the NextItem field. I have tried dt[,NextItem:= sample(x- ItemEaten,1),with=Name]




Aucun commentaire:

Enregistrer un commentaire