0

I want to replace NA in a dataframe column that is primarily a date with an old date.

I have tried various variations of the following based on other posts in stack overflow - but I can't seem to get the desired result.

sales$LatestSaleDate[as.character(sales$LatestSaleDate) == "NA"] <- as.Date("1900-1-1")

I get the error:

invalid factor level, NA generated.

I can't get my head around what is actually happening here.. but I am sure there is a simple workaround. Ideas?

  Sku  Name CustomList2ID LatestSaleDate LocalStock RemoteStock  is_in_stock  
1 sku1 Prd1             0     2017-05-12        -2           -2  out of stock  
2 sku2 Prd2             0     2017-05-22         5            5  in stock  
3 sku3 Prd3             0     <NA>              12           12  in stock  
4 sku4 Prd4             0     2017-05-19        -6           -6  out of stock  
5 sku5 Prd5             0     <NA>              -1           -1  out of stock  
6 sku6 Prd6             0     2017-05-25        33           33  in stock  
Martin Thompson
  • 3,415
  • 10
  • 38
  • 62
  • you have to use `is.na()` instead,....so: `sales$LatestSaleDate[is.na(sales$LatestSaleDate)] <- as.Date("1900-1-1")` – Tonio Liebrand May 25 '17 at 21:11
  • 1
    Possible duplicate of [How do I replace NA values with zeros in an R dataframe?](https://stackoverflow.com/questions/8161836/how-do-i-replace-na-values-with-zeros-in-an-r-dataframe) – Tonio Liebrand May 25 '17 at 21:14

1 Answers1

-1

Try using this -

sales$LatestSaleDate[is.na(sales$LatestSaleDate)] <- as.Date("1900-1-1")

  • Nope - same error message Warning message: In `[<-.factor`(`*tmp*`, is.na(sales$LatestSaleDate), value = c(180L, : invalid factor level, NA generated – Martin Thompson May 25 '17 at 21:36
  • looks like your `LatestSaleDate variable` is a factor. If this is the case first you need to transform it into `Date` type, then you can run the code above – Bea May 25 '17 at 21:46