0

Say we have the following data:

user <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
score <- c(3, 3, 3, NA, 0, 0, 0, NA, NA, NA, NA, NA)
type <- c('new', 'recent', 'recent', 'old', 'recent', 'new', 'new', 'old', 'new', 'new', 'new', 'recent')
df <- data.frame(user, score, type)

Where the df looks like this:

   user score   type
1     1     3    new
2     1     3 recent
3     1     3 recent
4     1    NA    old
5     2     0 recent
6     2     0    new
7     2     0    new
8     2    NA    old
9     3    NA    new
10    3    NA    new
11    3    NA    new
12    3    NA recent

How can I complete the cases for each category of user (1, 2 and 3) when type == old and it has a score not equal to NA (so excludes user 3)?

I would like to have a df like this:

   user score   type
1     1     3    new
2     1     3 recent
3     1     3 recent
4     1     3    old
5     2     0 recent
6     2     0    new
7     2     0    new
8     2     0    old
9     3    NA    new
10    3    NA    new
11    3    NA    new
12    3    NA recent

juanjedi
  • 140
  • 1
  • 7

1 Answers1

0

I found it myself!

df %>%
  group_by(user) %>%
  fill(score) %>%
  fill(score, .direction = "down")
juanjedi
  • 140
  • 1
  • 7