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 0
s and 1
s only, where each pair has only one 0
and one 1
.