0

I'm working with some datasets in R and, despite being able to solve my problem with base R, I'm really curious to know how to solve it with data.table, as I really made it the hard way.

I have the following data table:

head(assets)
date   XPTO ACME
1: 2011-05-31 669.1328 50.25
2: 2011-06-01 674.6444 49.77
3: 2011-06-02 657.3590 49.85
4: 2011-06-03 NA 49.43
5: 2011-06-06 667.0009 49.05
6: 2011-06-07 NA 48.96

I need to replace every NA with the value right before it, like in a for loop (I'll skip the for statement to make it short):

ifelse(is.na(assets[i])==TRUE, assets[i]<-assets[i-1], assets[i]<-assets[i])

Is there a way to do such a task with data.table syntax?

2 Answers2

0

Would the fillNAgaps function listed here work? You can just change the firstBack argument as appropriate. If you have two NAs in a row, I believe it'll put the same one again, if that's what you're looking for.

L. South
  • 141
  • 8
0

You can use zoo::na.locf().

assets[,XPTO := zoo::na.locf(XPTO)]

To answer jblood94 question, this function fills all NAs with the latest Non-NA value.

AndreasNearchou
  • 128
  • 1
  • 6