Home > Enterprise >  na.locf in data.table conditional on contents of a row
na.locf in data.table conditional on contents of a row

Time:06-09

I have a data.table where I want to carry forward the last observation. A sample from my data table looks as follows:

      V1     V2     V3     V4     V5     V6
1 Bond 1 Bond 1 Bond 1 Bond 2 Bond 2 Bond 2
2  Yield Coupon Rating  Yield Coupon Rating
3   <NA>   0.11      A      1   0.25     AA
4   <NA>   <NA>   <NA>      2   <NA>   <NA>
5      3   <NA>   <NA>      3   <NA>   <NA>
6      4   <NA>   <NA>      4   <NA>   <NA>
7      5   <NA>   <NA>      5   <NA>   <NA>

structure(list(V1 = c("Bond 1", "Yield", NA, NA, "3", "4", "5"
), V2 = c("Bond 1", "Coupon", "0.11", NA, NA, NA, NA), V3 = c("Bond 1", 
"Rating", "A", NA, NA, NA, NA), V4 = c("Bond 2", "Yield", "1", 
"2", "3", "4", "5"), V5 = c("Bond 2", "Coupon", "0.25", NA, NA, 
NA, NA), V6 = c("Bond 2", "Rating", "AA", NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-7L))

I want to carry out a na.locf when the second row contains the word Coupon. My target data.table would look like the following:

      V1     V2     V3     V4     V5     V6
1 Bond 1 Bond 1 Bond 1 Bond 2 Bond 2 Bond 2
2  Yield Coupon Rating  Yield Coupon Rating
3   <NA>   0.11      A      1   0.25     AA
4   <NA>   0.11   <NA>      2   0.25   <NA>
5      3   0.11   <NA>      3   0.25   <NA>
6      4   0.11   <NA>      4   0.25   <NA>
7      5   0.11   <NA>      5   0.25   <NA>

I have tried something like

dt[, if(dt[2,]=="TR.ADF_COUPON") na.locf]

But this isn't working.

CodePudding user response:

If I understood your question correctly:

df[,lapply(.SD,function(x) {if (x[2]=="Coupon") {zoo::na.locf(x)} else x})]

       V1     V2     V3     V4     V5     V6
1: Bond 1 Bond 1 Bond 1 Bond 2 Bond 2 Bond 2
2:  Yield Coupon Rating  Yield Coupon Rating
3:   <NA>   0.11      A      1   0.25     AA
4:   <NA>   0.11   <NA>      2   0.25   <NA>
5:      3   0.11   <NA>      3   0.25   <NA>
6:      4   0.11   <NA>      4   0.25   <NA>
7:      5   0.11   <NA>      5   0.25   <NA>
  • Related