Alexander
Alexander

Reputation: 4645

Conditional data labeling with comparing previous and next rows

having following type of data and want to re-label its NA rows by checking i-1 and i+1 rows of the NA rows.

test <- data.frame(sd_value=c(77,18,3,16,32,76),  
                   value=c(5400,6900,7080,1892,4207,4403), 
                   label=c(c("good",NA,"unable"),c("bads",NA,"good")))

> test
  sd_value value  label
1       77  5400   good
2       18  6900   <NA>
3        3  7080 unable
4       16  1892   bads
5       32  4207   <NA>
6       76  4403   good

The condition I want to re-label NA rows are

in simple picture: compare previous and next rows value to the NA row. if difference is <200 use the label of that row for NA row.

There is one special condition for if the previous or next row is good.

  1. if difference between i-1 or i+1 row of NA and diff(value) <200 and same as for diff(sd_value) <50 use i-1 or i+1 row's label that meets the condition.

  2. if difference i+1 is labeled good and row diff(value)<200 and same as for diff(sd_value)<50 use new eww! label.

the expected output

> test
      sd_value value  label
    1       77  5400   good
    2       18  6900 unable
    3        3  7080 unable
    4       16  1892   bads
    5       32  4207   eww!
    6       76  4403   good

checking diff values i-1 and i+1

> test%>%
+   mutate(diff_val=c(0,diff(value)), diff_sd_val=c(0,diff(sd_value)))

  sd_value value  label diff_val diff_sd_val
1       77  5400   good        0           0
2       18  6900   <NA>     1500         -59
3        3  7080 unable      180         -15
4       16  1892   bads    -5188          13
5       32  4207   <NA>     2315          16
6       76  4403   good      196          44

Upvotes: 2

Views: 151

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

Disclaimer: I have used the developer version of manymodelr(to save time) which I wrote.

library(manymodelr) 
library(dplyr)
res<-rowdiff(test,"reverse")
names(res)<-c("sd_diff","diff_val")

#if difference between i-1 or i+1 row of NA 
#and diff(value) <200 and same as for diff(sd_value) <50 use i-1 or i+1 row's 
#label that meets the condition.
#if difference i+1 is labeled good and row diff(value)<200 and 
#same as for diff(sd_value)<50 use new eww! label.
df_bound<-cbind(test,res)
df_bound %>% 
  mutate(label=ifelse(is.na(label) & lead(label,1)=="good","eww",label),
         label=ifelse(is.na(label) & lead(diff_val,1)<200,lead(label,1),label))

Result: NAs can be replaced with 0. sd_diff and diff_val can be removed.

sd_value value  label sd_diff diff_val
1       77  5400   good      NA       NA
2       18  6900 unable     -59     1500
3        3  7080 unable     -15      180
4       16  1892   bads      13    -5188
5       32  4207    eww      16     2315
6       76  4403   good      44      196

Upvotes: 2

Related Questions