'How to re-assign treatment in R
I have a data set of 1000 individuals with six columns where:
id - unique id number
supporter - whether they support a campaign or not (total of 50/1000)
D - whether they received treatment
donate - whether they donated to a campaign
thermo - score on a feeling thermometer (irrelevant for the question)
degree - total number of friends on a network (irrelevant for the question)
Sample data:
id supporter D donate thermo
1 1 0 0 0 46
2 2 0 1 1 49
3 3 0 0 0 58
4 4 0 1 1 17
5 5 1 0 0 51
6 6 0 0 0 69
7 7 0 0 0 18
8 8 0 0 0 69
9 9 0 0 0 75
10 10 0 0 0 48
11 11 0 0 0 39
12 12 0 0 0 56
13 13 0 0 0 67
14 14 0 0 0 67
15 15 0 0 0 41
16 16 1 1 1 69
17 17 0 0 0 38
18 18 0 0 0 37
19 19 0 0 0 50
20 20 0 0 0 54
I need to re-randomize treatment. Basically what I have to do, is to identify the 50 individuals that are supporters, assign half of them to treatment and half to control (D denotes this), but the rest has to stay the same.
Any ideas on how to do this?
Thank you!
Solution 1:[1]
We could do something like this:
Here with a sample of 10.
You have to change 10 to 50 and 5 in sample(id1, 5, ...
in 25:
library(dplyr)
set.seed(123)
df %>%
slice_sample(n = 10, replace = FALSE) %>%
mutate(id1=row_number()) %>%
mutate(D1 = case_when(row_number() %in%
sample(id1, 5, replace = FALSE) ~ 1, TRUE ~ 0)) %>%
right_join(df, by="id") %>%
mutate(D = coalesce(D1, D.y)) %>%
arrange(supporter.y) %>%
select(id, supporter=supporter.y, D, donate=donate.y, thermo = thermo.y)
id supporter D donate thermo
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 0 0 0
2 2 2 0 1 1
3 3 3 0 0 0
4 4 4 1 1 1
5 5 5 1 0 0
6 6 6 0 0 0
7 7 7 1 0 0
8 8 8 0 0 0
9 9 9 0 0 0
10 10 10 0 0 0
11 11 11 0 0 0
12 12 12 0 0 0
13 13 13 0 0 0
14 14 14 1 0 0
15 15 15 0 0 0
16 16 16 1 1 1
17 17 17 0 0 0
18 18 18 0 0 0
19 19 19 0 0 0
20 20 20 1 0 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TarJae |