0

Here is my code

library(ISLR)
attach(Weekly)

train = (Weekly$Year < 2009)
Weekly.0910 = Weekly[!train, ]

glm.fit3 = glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)
glm.fit4 = glm(Weekly$Direction ~ Weekly$Lag2, data = Weekly, family = binomial, subset = train)

glm.probs3 = predict.glm(glm.fit3, Weekly.0910, type = "response")
glm.pred3 = rep("Down" length(glm.probs3))
glm.pred3[glm.probs3 > 0.5] = "Up"

Direction.0910 = Direction[!train]
conf_mat2 = table(glm.pred3, Direction.0910)

the code above works as expected, but if I use glm.fit4 instead (even though its should be identical to glm.fit3), replacing the references to glm.fit3 with glm.fit4 then I get this error

Error in table(glm.pred4, Direction.0910) :

all arguments must have the same length

In addition: Warning message:

'newdata' had 104 rows but variables found have 1089 rows

Community
  • 1
  • 1
FatTail
  • 99
  • 1
  • 4
  • 2
    Yeah, don't use the dollar sign in the formula. `glm` has a `data` argument so you don't need `$`. Also don't `attach`. – Gregor Thomas Oct 24 '16 at 18:41
  • If i run this in R studio via source(program_name.R), then i need to use attach function ?. What is alternative – FatTail Oct 24 '16 at 18:54
  • 3
    I think you may have misunderstood. The whole point of functions having a `data` argument (i.e. `data = Weekly`) is that the formula may then be specified entirely in terms of the names of the columns, and R will look for those columns in that data frame. You can construct the formula from character vectors, if need be, but you should never, ever need to do `data$y ~ data$x, data = data`, it's redundant and prone to error. – joran Oct 24 '16 at 19:00
  • 1
    And there is not an alternative for `attach` - it is not necessary. It is a shortcut to let you refer to your data columns without the dollar sign for functions that *don't* have a `data` argument, but it usually causes more problems than it solves. You don't appear to be using its functionality at all, so you can just delete the line `attach(Weekly)`. – Gregor Thomas Oct 24 '16 at 19:04

1 Answers1

0

Updated code, thanks.

library(ISLR)
train = (Weekly$Year < 2009)
Weekly.0910 = Weekly[!train, ]
glm.fit = glm(Direction ~ Lag2, data = Weekly, family = binomial, subset = train)
glm.probs = predict.glm(glm.fit,newdata= Weekly.0910, type = "response")
glm.pred = rep("Down", length(glm.probs))
glm.pred[glm.probs > 0.5] = "Up"
Direction.0910 = Weekly$Direction[!train]
conf_mat = table(glm.pred, Direction.0910)
FatTail
  • 99
  • 1
  • 4