Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New variable that indicates the first occurrence of a specific value

I want to create a new variable that indicates the first specific observation of a value for a variable.

In the following example dataset I want to have a new variable "firstna" that is "1" for the first observation of "NA" for this player.

game_data <- data.frame(player = c(1,1,1,1,2,2,2,2), level = c(1,2,3,4,1,2,3,4), points = c(20,NA,NA,NA,20,40,NA,NA))

game_data
  player level points
1      1     1     20
2      1     2     NA
3      1     3     NA
4      1     4     NA
5      2     1     20
6      2     2     40
7      2     3     NA
8      2     4     NA

The resulting dataframe should look like this:

game_data_new <- data.frame(player = c(1,1,1,1,2,2,2,2), level = c(1,2,3,4,1,2,3,4), points = c(20,NA,NA,NA,20,40,NA,NA), firstna = c(0,1,0,0,0,0,1,0))

game_data_new
  player level points firstna
1      1     1     20       0
2      1     2     NA       1
3      1     3     NA       0
4      1     4     NA       0
5      2     1     20       0
6      2     2     40       0
7      2     3     NA       1
8      2     4     NA       0

To be honest i don't know how to do this. It would be perfect if there is a dplyr option to do so.

like image 545
Scijens Avatar asked Nov 30 '22 08:11

Scijens


1 Answers

A base R solution:

ave(game_data$points, game_data$player,
    FUN = function(x) seq_along(x) == match(NA, x, nomatch = 0))
like image 185
nicola Avatar answered Dec 04 '22 13:12

nicola