Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format of R's lm() Formula with a Transformation

I can't quite figure out how to do the following in one line:

data(attenu)
x_temp = attenu$accel^(1/4)
y_temp = log(attenu$dist)
best_line = lm(y_temp ~ x_temp)

Since the above works, I thought I could do the following:

data(attenu)
best_line = lm( log(attenu$dist) ~ (attenu$accel^(1/4)) )

But this gives the error:

Error in terms.formula(formula, data = data) : invalid power in formula

There's obviously something I'm missing when using transformed variables in R's formula format. Why doesn't this work?

like image 343
nfmcclure Avatar asked Jun 19 '15 02:06

nfmcclure


People also ask

What is the general format of the lm () function?

The lm() function Note that the formula argument follows a specific format. For simple linear regression, this is “YVAR ~ XVAR” where YVAR is the dependent, or predicted, variable and XVAR is the independent, or predictor, variable.

How do you write an lm equation in R?

To fit a linear model in the R Language by using the lm() function, We first use data. frame() function to create a sample data frame that contains values that have to be fitted on a linear model using regression function. Then we use the lm() function to fit a certain function to a given data frame.

What does the R function lm () do?

Summary: R linear regression uses the lm() function to create a regression model given some formula, in the form of Y~X+X2. To look at the model, you use the summary() function. To analyze the residuals, you pull out the $resid variable from your new model.


Video Answer


1 Answers

You're looking for the function I so that the ^ operator is treated as arithmetic in the formula, ie.

x <- runif(1:100)
y <- x + rnorm(100,0, 3)
lm(log(y) ~ I(x^(1/4))
like image 50
Rorschach Avatar answered Sep 23 '22 08:09

Rorschach