0
votes

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.

1
When I run your code, there is a new column 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 your dataset data.frame?MrFlick
The second observation does change from -55 to 55. Maybe there's a typo in your R file? because this code is working just fine.Salix

1 Answers

0
votes

Thanks for the help, I figured out the issue. It was a dumb one too. My var3 variable was set as an integer variable instead of as a numeric variable and when I switched it, it worked for some reason.

dataset$var3 <- as.integer(dataset$var3)

That did the trick.