tef2128
tef2128

Reputation: 780

Error using effects package in R; wrong variable type

While investigating some fundamentals of multiple regression, I decided to try and compare my manual efforts to those of the "effects" package, by John Fox. I've generated variables with some relationships, and want to get adjusted means for a factor when controlling for the influence of a continuous variable.

I have become stalled, however, as the effect function in the effects package returns an error "invalid type (builtin) for variable 'c'"

When I check the type of variable 'c' using typeof(c), I'm told it is of type double, as I constructed it to be.

Here is my code:

set.seed(1986)
y <- rnorm(100)
f <- sapply(y, function(x) if(x < 0) 1 else 2)
f.f <- as.factor(f)
set.seed(1987)
c <- rnorm(100, 0, .1) + y + f

an3 <- lm(y ~ f.f + c); summary(an3)

ef <- effect("f.f", an3)

Upvotes: 0

Views: 564

Answers (2)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37754

Another option is to store the data in a data.frame; this has other benefits as well, especially if one is working with multiple data sets.

set.seed(1986)
d <- data.frame(y=rnorm(100))
d <- within(d, {
  f <- sapply(y, function(x) if(x < 0) 1 else 2)
  f.f <- as.factor(f)
  set.seed(1987)
  c <- rnorm(100, 0, .1) + y + f
})

library(effects)

an3 <- lm(y ~ f.f + c, data=d); summary(an3)
ef <- effect("f.f", an3)
ef

# f.f effect
# f.f
#          1          2 
#  0.5504214 -0.3231941 

Upvotes: 0

Ari B. Friedman
Ari B. Friedman

Reputation: 72741

c is not a good choice for a a variable name. It's an extremely commonly-used built-in function in R.

Changing c to d works for me:

set.seed(1986)
y <- rnorm(100)
f <- sapply(y, function(x) if(x < 0) 1 else 2)
f.f <- as.factor(f)
set.seed(1987)
d <- rnorm(100, 0, .1) + y + f

an3 <- lm(y ~ f.f + d); summary(an3)

library(effects)
ef <- effect("f.f", an3)
 ef

 f.f effect
f.f
         1          2 
 0.5504214 -0.3231941 

Upvotes: 3

Related Questions