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.