user4579
user4579

Reputation: 103

Converting characters to numeric in dataframe

Suppose I have a dataframe, "Election2000" with a column factor "presvote". Presvote has 3 possible values: "republican", "democrat", "NA".

How do I create a new variable, RVote, that converts all republican values to the value 1, and democrat values to 0?

Upvotes: 0

Views: 120

Answers (1)

Lizzie Silver
Lizzie Silver

Reputation: 293

The command you are looking for is:

Election2000$RVote <- as.numeric(Election2000$presvote=="republican")

Edit: It works with this example data frame:

presvote <- c("democrat", "republican", "democrat", NA, "republican")
Election2000 <- data.frame(presvote)
Election2000$presvote <- as.factor(Election2000$presvote)

Upvotes: 2

Related Questions