leeper / margins

An R Port of Stata's 'margins' Command
https://cloud.r-project.org/package=margins
Other
260 stars 40 forks source link

Error from data.table::rbindlist when there is a Survival object in data, even if not in model #149

Open jay-sf opened 4 years ago

jay-sf commented 4 years ago

Hi,

first of all thanks a ton for providing marginal effects for R!

I've identified an issue when there's a survival object in the data set. data.table::rbindlist won't like it at the moment and throws an error. The issue happens even if the object is not in the model.

Thank you if you could take a look into this.

Cheers!

MCVE:

str(dat)
# 'data.frame': 5 obs. of  3 variables:
# $ y: num  -2.9816 1.6618 -0.0912 1.3168 0.7922
# $ x: num  0.194 -1.116 -0.125 -0.679 -1.658
# $ s: 'Surv' num [1:5, 1:3] 0- 0- 0- 0- ...
# ..- attr(*, "dimnames")=List of 2
# .. ..$ : NULL
# .. ..$ : chr [1:3] "time1" "time2" "status"
# ..- attr(*, "type")= chr "interval"

fit1 <- lm(y ~ x, dat)  ## with survival object in data
margins::margins(fit1)
# Error in data.table::rbindlist(list(d0, d1)) : 
#  Column 1 of item 1 is length 5 inconsistent with column 3 which is length 15. 
#  Only length-1 columns are recycled.

fit2 <- lm(y ~ x, dat[-3])  ## survival object removed from data 
margins::margins(fit2)
# Average marginal effects
# lm(formula = y ~ x, data = dat[-3])
# 
#       x
#  -1.874

## Data
dat <- structure(list(y = c(-2.98156392748949, 1.66179894021854, -0.0912380677316067, 
1.31682259604163, 0.792210663360883), x = c(0.194347777395277, 
-1.11603405271533, -0.125314349609543, -0.679074978115255, -1.6581749663707
), s = structure(c(0, 0, 0, 0, 9, 1, 1, 1, 1, 1, 2, 2, 2, 2, 
1), .Dim = c(5L, 3L), .Dimnames = list(NULL, c("time1", "time2", 
"status")), type = "interval", class = "Surv")), class = "data.frame", row.names = c(NA, 
-5L))

## Session Info
R version 4.0.1 RC (2020-05-30 r78647)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] margins_0.3.23

loaded via a namespace (and not attached):
[1] MASS_7.3-51.6     compiler_4.0.1    tools_4.0.1       data.table_1.12.8 prediction_0.3.14
leeper commented 4 years ago

Thanks - this might need to be fixed upstream in data.table but I'll investigate if there's anything we can do here. If you find a solution in the meantime, I'd accept a PR.

msonderegger commented 3 years ago

This looks like it overlaps with #171 ?