how can i add two columns to a data table with random sampling of a binary possibility?

You could first assign right (or left) and then assign the opposite one to other side.

library(data.table)

children <- data.table(child = c("Gertrude", "Penelope", "Joshua", 
                                  "Sebastian", "Jane", "Ravi"))

children[, right := sample(c('in', 'out'), .N, replace = TRUE)]
children[, left := fifelse(right == 'in', 'out', 'in')]
children

#       child right left
#1:  Gertrude    in  out
#2:  Penelope    in  out
#3:    Joshua   out   in
#4: Sebastian   out   in
#5:      Jane   out   in
#6:      Ravi    in  out

To add two columns in one go we need output to be a list.

children[, c("right", "left") := as.list(sample(c("in", "out"))), children]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top