Reputation: 1
I'm trying to create a binary variable as answer to another binary variable
This is the gpa2 dataset from wooldridge library. I tried to create the variable male with a while loop too but it still doesn't work. I've already tried adding else statements but it didn't work.
library(wooldridge)
gpa2 <- gpa2
for(i in 1:length(gpa2$female)){
if(gpa2$female == 0 ){
gpa2$male = 1
}
}
I expect male be 0 when female is 1 and male be 1 when female is 0, but the output I get is male = 0 for every observation.
Upvotes: 0
Views: 305
Reputation: 7592
gpa2$male<-as.numeric(!gpa2$female)
You're really missing out on R if you do everything with for-loops. More often than not, there's a much faster way of doing what you're trying to do using r's in-built ability to vectorize actions. In this case, we simply take gpa2$female
, use !
to flip 0's into TRUEs and 1's into FALSEs, and then turn that into a numeric format so they appear as 1s and 0s respectively, and place that whole vector into gpa2$male
.
Upvotes: 1