Home > database >  Create new column based on condition and give new column a sum of a created value of existing column
Create new column based on condition and give new column a sum of a created value of existing column

Time:07-08

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?

CodePudding user response:

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))
)
  • Related