Joye
Joye

Reputation: 13

Variable(s)have been specified in ‘linfct’ but cannot be found in ‘model’!

I want to run a multiple comparisons analysis for the different variables of a model. My idea is as follows:

a
   V1   V2
1  t1  5.0
2  t1  4.0
3  t1  2.0
4  t1  5.0
5  t1  5.0
6  t2  4.0
7  t2  3.0
8  t2  4.0
9  t2  9.0
10 t2  3.0
11 t3  2.0
12 t3  3.0
13 t3  2.0
14 t3  6.0
15 t3  8.0

tuk<-glht(fit,linfct=mcp(a$V1="Tukey"))

when I run, it showed :

“Variable(s) ‘trt’ have been specified in ‘linfct’ but cannot be found in ‘model’!”

I don't know how to deal with it。

Upvotes: 0

Views: 15358

Answers (2)

I had the same issue and the problem seems to lie in the way the model is declared. It won't work if you use:

fit <- lm(a$V2 ~ a$V1)

But it does if you declare the model as:

fit <- lm(V2 ~ V1, data = a)

Upvotes: 0

Achim Zeileis
Achim Zeileis

Reputation: 17183

It appears that you somehow changed the name of the data and/or the variables between computing your fit and calling glht. Your code has V1 but the error has trt. It's hard to say more in detail because your example is not fully reproducible (the computation of fit is missing). If I re-run what I assume you did (or should have done), everything works smoothly.

First, let's read the data:

a <- read.table(textConnection("   V1   V2
1  t1  5.0
2  t1  4.0
3  t1  2.0
4  t1  5.0
5  t1  5.0
6  t2  4.0
7  t2  3.0
8  t2  4.0
9  t2  9.0
10 t2  3.0
11 t3  2.0
12 t3  3.0
13 t3  2.0
14 t3  6.0
15 t3  8.0"), header = TRUE)

Then, we can fit what I assume is supposed to be a linear model with response V2 and explanatory variable V1:

fit <- lm(V2 ~ V1, data = a)

And then the multcomp package can be called:

library("multcomp")
summary(glht(fit, linfct = mcp(V1 = "Tukey")))
##          Simultaneous Tests for General Linear Hypotheses
## 
## Multiple Comparisons of Means: Tukey Contrasts
## 
## Fit: lm(formula = V2 ~ V1, data = a)
## 
## Linear Hypotheses:
##                Estimate Std. Error t value Pr(>|t|)
## t2 - t1 == 0  4.000e-01  1.424e+00   0.281    0.958
## t3 - t1 == 0  5.617e-16  1.424e+00   0.000    1.000
## t3 - t2 == 0 -4.000e-01  1.424e+00  -0.281    0.958
## (Adjusted p values reported -- single-step method)

Upvotes: 1

Related Questions