I am trying to create a new variable in a dataset based on if certain conditions of the observation are met. For example, I have a dataset like:
dataset <- read.table(text="var1 var2 var3
67 Home 1
-55 Away 1
-36 Away 0
12 Home 0", header=TRUE)
and I want to create a variable dataset$var4 that takes the opposite of var1 (multiplies it by -1) if and only if var2 = "Away" and var3 = 1. If those conditions aren't met, I would like it to input the original value for var1 for that observation. My code looks like this:
dataset$var4 <- ifelse(dataset$var2 == "Away" & dataset$var3 == 1, dataset$var1*-1, dataset$var1)
With the example dataset above, the second observation should be the only one to change to its opposite (from -55 to 55). However, when I do this the none of the numbers change at all. Anyone know what I am doing wrong?
EDIT: To clarify, the conditions in the ifelse statement should be correct. That is, when I input:
which(dataset$var2 == "Away" & dataset$var3 == 1)
it returns "2" meaning the second observation is recognized to fit the conditions.
var4
created and the second value turned from -55 to 55 so it seems to be working for me. So you saying you are not getting an additional column in yourdataset
data.frame? – MrFlick