0

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?

1
  • 4
    This question appears to be off-topic because it is about how to use R w/o a reproducible example. Commented Nov 10, 2014 at 22:13

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

6 Comments

Election2000$presvote automatically assigns numeric values 1, and 2 to republican and democrat. How do I switch these to 1 and 0 instead?
@user4579 I need to see what you're looking at to know how to answer that. When you type Election2000$presvote , what does R return? Is it a factor column, or a numeric one?
A factor column. I need to switch the factors from 1,2 to 0,1 to run logit and probit regressions
@user4579 then I think the line above should work: Election2000\$RVote <- as.numeric(Election2000\$presvote=="republican") . But if it does not, try: Election2000\$RVote <- as.numeric(as.numeric(Election2000\$presvote)==2) . You should then have a new column, RVote, containing 0, 1 and NA values.
@user4579 or more concisely: Election2000$RVote <- as.numeric(Election2000$presvote)-1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.