0

I am trying to create a new column based on a condition of another condition, creating a new column by giving it a self-determined value and (a part of) the value of an existing column. My code looks like this:

Output <- mutate(data, new variable = if_else(variableA=="A", "0.060 + VariableC*0.03",
                                      if_else(variableA=="B", "0.050",
                                               "NA")))

This code works when I create a new variable with the values 0.060 and 0.050 (without the part 'VariableC*0.03).

However, I want the variable 'VariableC' also multiplied by 0.03 and summed up by the value 0.060 for A. Can anyone help me with this problem?

Wutruvic
  • 83
  • 7
  • Tried it without quotation marks, but it isn't working either. – Wutruvic Jul 07 '22 at 12:47
  • One name is a lower-case "v" and the other is upper-case "V", are you certain that the names are case-correct? FYI, you say "it isn't working", we can't help if we don't have more information. Please make this *reproducible* including sample data and the literal text of errors/warnings. See https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Jul 07 '22 at 12:54
  • It could also be that this code does not parse correctly: `new variable` cannot be a variable name with an embedded space. If you need that space, then you need to enclose it in backticks here as in `mutate(data, \`new variable\` = if_else(...))`. – r2evans Jul 07 '22 at 12:55
  • I understand that making a question reproducible will help for better answers, however my data is personal and therefore I cannot share it. Maybe I can show my problem with a more general dataset. – Wutruvic Jul 07 '22 at 13:03

1 Answers1

2

I think the major issue you made here is enclosing the resulting values in quotes. This treats them like they are literal strings. Also, use NULL to keep the type double for your new_variable. Try this:

Output <- mutate(data, 
  new_variable = if_else(variableA=="A", 0.060 + VariableC * 0.03,
                         if_else(variableA=="B", 0.050, NULL)))                                          

This works for me with a different dataset, which you can try out:

library(dslabs)
data(murders)
Output <- murders %>% mutate(
  new_variable = if_else(
   state == "Alabama",
   0.060 * total * 0.03,
   if_else(state == "Alaska", 0.050, NULL))
)
Oli
  • 9,766
  • 5
  • 25
  • 46