I have a simple problem but can't seem to figure out what I'm doing wrong. I am using predict
to estimate values from a fitted linear model. The following code works correctly:
x <- c(1, 2, 3, 4, 5 , 6)
y <- c(1, 4, 9, 16, 25, 36)
model <- lm(y ~ x)
predict(model, newdata = data.frame(x=7))
However, when I use the same data for x and y, but in a dataframe, it does not work. For example,
df2 <- structure(list(x = c(1, 2, 3, 4, 5, 6), y = c(1, 4, 9, 16, 25,36)),
.Names = c("x", "y"), row.names = c(NA, -6L), class = "data.frame")
model <- lm(df2$y ~ df2$x)
predict(model, newdata = data.frame(x=7))
throws the error:
Warning message:
'newdata' had 1 row but variables found have 6 rows
I am using the same exact data and am expecting the same answer. Can anyone tell me what I am doing wrong? Thanks!