How can I add two columns to a data.table with random sampling of a binary possibility?

Viewed 37

I have a data table of children where I know one ear was affected but I do not know which one. I want to randomly allocate the issue to either the right ear or the left ear. I do not care which but if the one ear is designated "in" then the other ear must be designated "out".

That is easy I thought for just one child

sample(c("in", "out"), size = 2)

Then I thought that I could simply assign the results to the right and left column.

children <- data.table(child = c("Gertrude", "Penelope", "Joshua", "Sebastian", "Jane", "Ravi"))
children[, c("right", "left") := sample(c("in", "out"), size = 2)]

I have messed around a lot with the code and I keep getting the following message. It is not helping me.

Error in [.data.table(children, , :=(c("right", "left"), sample(c("in", : Supplied 2 items to be assigned to 6 items of column 'right'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

I also tried adding by=child.

Can you please help me?

1 Answers

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