AntVal
AntVal

Reputation: 665

Create new variable with if else condition in R

I know there are many queries like this, but I tried different things and I couldn't solve my issue:

So I have a dataset with voting percentages but they're defined differently for different referendums, and I want to create a new column that is the difference between a variable's value if a condition is met, or just keep that variable's value if the condition is not met. Basically for certain referendums for it to keep the percentage value it has and for others to calculate the difference between 100 and the value it has now. Something like this:

id <- c(1, 2, 3)
yes.perc <- c(66.7, 50, 49)
ref.code <- c(6040,6041,6042)
df <- as.data.frame(c(id, percentage, ref)

I tried this, for example:

df%>%
 mutate(vote=ifelse(ref.code == 6040|6041, (100-yes.perc), print(yes.perc)))

And:

df%>%
 mutate(vote=ifelse(ref.code == 6040|6041, 100-yes.perc, yes.perc))

And a lot of similar things, but I keep on getting the difference (100-yes.perc) printed for all rows, no matter whether they meet the condition or not. I have also tried to change the "ref.code" variable to a factor or numeric, but didn't make much difference. Thanks!

Upvotes: 0

Views: 564

Answers (2)

tpetzoldt
tpetzoldt

Reputation: 5813

library("dplyr")

df <- data.frame(
  id = 1:3,
  percentage = c(66.7, 50, 49),
  ref = c(6040, 6041, 6042)
)


df %>%
  mutate(vote = ifelse(ref %in% c(6040, 6041), 100 - percentage, percentage))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389135

1) | is used in regex, here you need to use %in%

2) Don't print in ifelse

library(dplyr)
df%>% mutate(vote=ifelse(ref.code %in% c(6040, 6041), (100-yes.perc), yes.perc))

#  id yes.perc ref.code vote
#1  1     66.7     6040 33.3
#2  2     50.0     6041 50.0
#3  3     49.0     6042 49.0

Upvotes: 1

Related Questions