user9272398
user9272398

Reputation:

how to print just coefficients of lm?

If I have one row of data,y, like this:

 1 4 5 6 3 4 

I can use the following code to find a fitted smooth curve :

y <- scan(text = '1 4 5 6 3 4 ')
x <- seq_along(y)
fit <- lm(y ~ poly(x,5))

summary(fit)   
newy <- predict(fit, data.frame(x))

plot(y, type = "b")
lines(x, newy, col = "red") 

I need to do the same for 600 rows and use summary(fit) to get the coefficients. My problem is that I have to use these coefficients in other software and I just need the coefficients, not extra information. Is there any way to print out just the coefficients?

Upvotes: 0

Views: 1971

Answers (2)

Jim O.
Jim O.

Reputation: 1111

If I understood your question correctly, you just want the numbers without any descriptors attached. Here it is:

y <- scan(text = '1 4 5 6 3 4 ')
x <- seq_along(y)
fit <- lm(y ~ poly(x,5))

z <- coef(fit)
names(z) <- NULL
z

[1]  3.833333  1.553797 -2.836833  1.341641  1.133893  1.133893

Just remember that the first item is the y-intercept.

Upvotes: 0

Ben Bolker
Ben Bolker

Reputation: 226182

It's just coef(fit). The coef() method should work for most statistical models in R: model$coefficients works for lm objects, but is not generally reliable. coef(summary(model)) or summary(model)$coefficients give a full coefficient table. (The default method for coef(), stats:::coef.default(), uses $coefficients to extract these values from the objects, but other model objects may work differently.)

Upvotes: 3

Related Questions