Search the vector / data table back in R

Basically, I have a very large data / data data table, and I would like to find a column for the first and closest value NAthat is smaller than my current index position.

For example, let's say I have a data frame DFas follows:

INDEX | KEY   |   ITEM
----------------------
 1    |  10   |    AAA
 2    |  12   |    AAA
 3    |  NA   |    AAA
 4    |  18   |    AAA
 5    |  NA   |    AAA
 6    |  24   |    AAA
 7    |  29   |    AAA
 8    |  31   |    AAA
 9    |  34   |    AAA

From this data frame, we have a value NAat index 3 and index 5. Now let's say that we start at index 8 (which has KEY31). I would like to find the column KEYback, so that the moment it finds the first instance NA, the search stops and the index of the value NA is returned.

, NA / (, which(is.na(x)) , NA), - - , , . , , - " ", , , , , ( , 100 000 , ).

, NA?

+2
1

NA , NA :

library(dplyr)
library(tidyr)

df = df %>%
    mutate(last_missing = if_else(is.na(KEY), INDEX, as.integer(NA))) %>%
    fill(last_missing)

:

> df
  INDEX KEY ITEM last_missing
1     1  10  AAA           NA
2     2  12  AAA           NA
3     3  NA  AAA            3
4     4  18  AAA            3
5     5  NA  AAA            5
6     6  24  AAA            5
7     7  29  AAA            5
8     8  31  AAA            5
9     9  34  AAA            5

, . , , , , .

+4

Source: https://habr.com/ru/post/1680685/


All Articles