0

I want to modify the lm() function of base R. Specifically, I don't want it to fail if all data is NA. Right now it fails with error: 0 (non-NA) cases.

I must call lm() within a data.table. There are more chaining and grouping procedures involved.

I wrote a wrapper for lm() but I don't know how to access the data argument. I can access the formula argument.

LM = function(...) {

  for(i in list(...)) {
    print(i);
  }

  lm(...);
}


> mydata[Date > "May 1951", lm(dep_var ~ ind_var)$coef[2], by = Date]
         Date          V1
  1: Jun 1951  0.56078961
  2: Jul 1951  0.03058471
  3: Aug 1951  0.67276820
  4: Sep 1951 -0.36109541
  5: Oct 1951  0.23469848


> mydata[Date > "May 1951", LM(dep_var ~ ind_var)$coef[2], by = Date]
dep_var ~ ind_var
<environment: 0x3662f3d0>

<<< repeat 4 times >>>

         Date          V1
  1: Jun 1951  0.56078961
  2: Jul 1951  0.03058471
  3: Aug 1951  0.67276820
  4: Sep 1951 -0.36109541
  5: Oct 1951  0.23469848

Below are failure cases:

> mydata[Date == "Jan 1926", LM(dep_var ~ ind_var)$coef[2], by = Date]
dep_var ~ ind_var
<environment: 0x99f14860>
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  0 (non-NA) cases
>
> mydata[Date == "Jan 1926", lm(dep_var ~ ind_var)$coef[2], by = Date]
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  0 (non-NA) cases
>

The data for "Jan 1926" is all NA and hence lm() fails. I want my wrapper function LM()to return NA for this case and continue working. I have played with na.action attribute but with no solution.

Nikhil Vidhani
  • 709
  • 5
  • 11
  • try `mydata[Date == "Jan 1926", if(!all(is.na(dep_var))) LM(dep_var ~ ind_var)$coef[2], by = Date] ` – chinsoon12 May 08 '19 at 01:00
  • 2
    You don't need to modify `lm`, you need to use `tryCatch` on your `lm` call to catch the error and handle it appropriately. (Or, perhaps just check the data before calling `lm`...) – Gregor Thomas May 08 '19 at 02:48
  • Suggested dupe: [How to write `tryCatch` in R?](https://stackoverflow.com/q/12193779/903061) – Gregor Thomas May 08 '19 at 02:49

0 Answers0