4

I have a data frame of the following format.

   author year stages
1  A 1150      1
2  B 1200      1
3  C 1200      1
4  D 1300      1
5  D 1300      1
6  E 1390      3
7  F 1392      3
8  G 1400      3
9  G 1400      3
...

I want to jitter each year and author combination by a small amount. I want documents by different authors in the same year to be jittered by unique values. For example, tokens from author B and C appear in the same year, but should be jittered by different amounts. All tokens from the same author, for example the two tokens from author G at 1400 should be jittered by the same amount.

I've tried the following, but get a unique jitter amount for each and every row.

data %>% group_by(author) %>% mutate(year = jitter(year, amount=.5))

The output of this code is the following.

   author     year stages
1  A 1150.400      1
2  B 1200.189      1
3  C 1200.222      1
4  D 1300.263      1
5  D 1299.788      1
6  E 1390.045      3
7  F 1391.964      3
8  G 1399.982      3
9  G 1399.783      3

However, I would like the following, where both tokens from author G should be shifted by the same amount. The crucial difference is that for author G all tokens are shifted by the same amount.

   author     year stages
1  A 1150.400      1
2  B 1200.189      1
3  C 1200.222      1
4  D 1300.263      1
5  D 1299.788      1
6  E 1390.045      3
7  F 1391.964      3
8  G 1399.982      3
9  G 1399.982      3
wdnsd
  • 223
  • 3
  • 11

1 Answers1

4

Calculate the jitter for one case and add the difference to all cases:

dat %>% 
  group_by(author) %>% 
  mutate(year = year + (year[1] - jitter(year[1], amount=.5)))

#  author     year stages
#1      A 1149.720      1
#2      B 1200.385      1
#3      C 1199.888      1
#4      D 1299.589      1
#5      D 1299.589      1
#6      E 1389.866      3
#7      F 1392.225      3
#8      G 1400.147      3
#9      G 1400.147      3
thelatemail
  • 91,185
  • 12
  • 128
  • 188