I have huge dataframe like this:
df <- read.table(text="
id date
1 1 2016-12-01
2 2 2016-12-02
3 4 2017-01-03
4 6 2016-11-04
5 7 2017-11-05
6 9 2017-12-06", header=TRUE)
I generate randomly 1 or 0 for each id. I'm doing it with this code.
set.seed(5)
df %>%
arrange(id) %>%
mutate(
rn = runif(id),
discount = if_else(rn < 0.5, 0, 1)
)
It works perfectly until I add new rows to my dataframe. Then are my random numbers different.
But what I need is not just generate random number for each id, but that number has to remain same even if new rows are added.
That means:
id date discount
1 1 2016-12-01 1
2 2 2016-12-02 0
3 4 2017-01-03 0
4 6 2016-11-04 1
5 7 2017-11-05 1
6 9 2017-12-06 1
When new rows are added
id date discount
1 1 2016-12-01 1
2 2 2016-12-02 0
3 4 2017-01-03 0
4 6 2016-11-04 1
5 7 2017-11-05 1
6 9 2017-12-06 1
7 12 2017-12-06 0
8 13 2017-12-06 1
Aucun commentaire:
Enregistrer un commentaire