jeudi 21 avril 2022

Generate random binary variable conditionally in R

I would like to add an extra column, z based on the following conditions:

  • if x == "A", generate a binary variable assuming the prob of success (=1) is 0.5
  • if x == "C" & y == "N", generate a binary variable assuming the prob of success is 0.25.
# Sample data
df <- tibble(
x = ("A", "C", "C", "B", "C", "A", "A"),
y = ("Y", "N", "Y", "N", "N", "N", "Y")) 

Currently, my approach uses filter, then set.seed and rbinom, and finally rbind. But I am looking for a more elegant solution that doesn't involve subseting and re-joining the data.




Aucun commentaire:

Enregistrer un commentaire