3

I am still new to R, so this may be a stupid question, but:

I have two variables (gender [0,1] and vote [0,1).

I want to merge the two variables into one variable with four different values:

1) Gender=0, Vote=0

2) Gender=1, Vote=0

3) Gender=0, Vote=1

4) Gender=1, Vote=1

I guess I will need the if command, but it somehow won't work out for me.

Hope, anyone can help me :)

4
  • Perhaps you need expand.grid i.e. expand.grid(gender=0:1, vote=0:1) Commented May 5, 2016 at 12:48
  • But how do I use that to generate a new variable in my data frame with values (1,2,3,4) dependent on the values on gender and vote for each observation. Right now, it only prints a short table. Commented May 5, 2016 at 12:59
  • Try Gender+2*Vote. Commented May 5, 2016 at 13:01
  • 1
    This is called the interaction of two factors. You need to convert your variables to factors and then call interaction(). Commented May 5, 2016 at 13:06

1 Answer 1

1

Here is one way to do it. akrun already post half of the solution in comment. There might be a better way though:

grid = expand.grid(gender=0:1, vote=0:1)
new_var = apply(grid,1,function(x) paste(x,collapse=""))
new_var = as.factor(new_var) # classic categorical format in R
Sign up to request clarification or add additional context in comments.

Comments

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.