1

I have a long list of paired interactions between people. I need to assign an initiator to each pair at random. Therefore, for each pair there will be one person assigned a 1 and the other will be assigned a 0.

I have tried to find an answer to this, since I believe it must have been solved somewhere. Unfortunately, I do not think I am managing to hit the right keywords. The following answer was the most useful:

Numbering rows within groups in a data frame

Here is some dummy code and where I am up to (real data has many more columns and rows):

dummy_data <- tibble(
  ID = c(1, 1, 2, 2, 3, 3),
  Sex = c("M", "F", "F", "M", "F", "M")
)

dummy_data <- dummy_data %>%
  group_by(ID) %>%
  mutate(initiator = ifelse(row_number() == 1,
                            sample(0:1, 1),
                            (1 - row_number()[1])
                           )
        )

The idea being here is that I will assign a random value to the first person of each pair, and then take the opposite value for the second person.

The issue I am having lies in the "false" part of the ifelse() function - I cannot seem to get the value of the previous row out.

The desired output is a new column consisting of 0s and 1s only, where each pair has only one 0 and one 1.

FitzKaos
  • 381
  • 3
  • 20

2 Answers2

1

If you have only two rows in each ID you could sample 0 and 1 and assign them randomly.

library(dplyr)

dummy_data %>%
 group_by(ID) %>%
 mutate(initiator = sample(0:1))

#     ID Sex   initiator
#   <dbl> <chr>     <dbl>
#1     1 M             0
#2     1 F             1
#3     2 F             1
#4     2 M             0
#5     3 F             1
#6     3 M             0
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

With data.table

library(data.table)
setDT(dummy_data)[, initiator := sample(0:1), ID]
akrun
  • 874,273
  • 37
  • 540
  • 662