panelr icon indicating copy to clipboard operation
panelr copied to clipboard

With a factor variable I get an error in "complete.cases(data[[variable]])"

Open jogrue opened this issue 4 years ago • 0 comments

I am running a simple model y ~ x. When I add a factor variable for the respondents' region (9 levels), drawing marginal effects plots (with sjPlot::plot_model) or computing marginal effects/means (with ggeffects::ggpredict) does not work anymore. I get this error:

Error in complete.cases(data[[variable]]) : 
  no input has determined the number of cases

Since complete.cases(data[[variable]]) is called in the expand_labels function in wb_utils.R, I guess this has something to do with how factors/labels are treated in panelr? If I manually add dummies instead of the factor variable, it works!

Here is some test data to reproduce it: testdata.zip

And that is the code for testing:

library(tidyverse)
library(ggeffects)
library(panelr)

testdata <- read_csv("~/testdata.csv")

# Problem with factor variable ------------------------------------------------

# Prepare data
testdata <- testdata %>%
  mutate(
    x2 = factor(x2)
  ) %>%
  panelr::panel_data(id = "id", wave = "wave")

# Run model
mod <- panelr::wbm(y ~ x1 | x2, data = testdata)
summary(mod)
ggeffects::ggpredict(model = mod)
# Error in complete.cases(data[[variable]]) :
#   no input has determined the number of cases

# With dummies this works -----------------------------------------------------
 
# Prepare data
dummies <- model.matrix(~x2 - 1, data = testdata) %>%
  as_tibble
testdata <- bind_cols(panelr::unpanel(testdata), dummies) %>%
  panelr::panel_data(id = "id", wave = "wave")

# Run model
mod <- panelr::wbm(y ~ x1 | x22 + x23 + x24 + x25 + x26 + x27 + x28 + x29,
                   data = testdata)
summary(mod)
ggeffects::ggpredict(model = mod)

jogrue avatar Jul 11 '20 09:07 jogrue