Nikeli
Nikeli

Reputation: 19

How can I create a dummy using factor() with the mtcars data?

I get the message:

Error in factor(carb) : Object 'carb' not found.

But it should find carb, because it is in the data.

I can create a factor for "am" using

mtcars$amf <- factor(mtcars$am, labels=c("automatic", "manual"))

Import data:

data(mtcars)

Define factor variable:

mtcars$carbf <- factor(carb)

Then I get the error message:

Error in factor(carb) : Object 'carb' not found.

What I expect is that a categorical variable is automatically included as a set of dummy variables if it is defined as factor variable.

So when I would run

lm(mpg~wt+carbf, data=mtcars)

it would get me a output with dummy variables?

Upvotes: 1

Views: 151

Answers (1)

MDEWITT
MDEWITT

Reputation: 2368

carb doesn't exist in the global environment, only in the context of the data frame. Because of that you need to reference explicitly.

See below:

mtcars$carbf <- factor(mtcars$carb)

Upvotes: 1

Related Questions