Consider the following data:
Names <- c("name1", "name2", "name3", "name4", "name1")
Methods <- c("method1","method2", "method2", "method1", "method2")
Amount <- c(5, 10, 15, 20, 25)
df <- data.frame(Names, Methods, Amount)
I want to create a new variable for the dataframe based on a condition within a condition of the df as a new column. I tried it based on 1 conditions and that worked:
df <- mutate(df, new_column = if_else(Methods=="method2", 0.05 Amount * 1.5, NULL))
However how can I get a condition within this condition, to get for example:
name1 with method 2 and then give the new_column a value of 0.25 amount * 0.5 ?
I tried the following code:
df <- mutate(df, new_column = if_else(Names=="name1",
if_else(Methods=="method2", 0.25 Amount * 0.5, NULL)))
Can anybody help me please?
CodePudding user response:
You could use:
mutate(df, new_column = ifelse(Methods=="method2" & Names=="name1", 0.05 Amount * 1.5,
ifelse(Names=="name2", 0.05 Amount * 1.5, NA
)))
Names Methods Amount new_column
1 name1 method1 5 7.55
2 name2 method2 10 15.05
3 name3 method2 15 22.55
4 name4 method1 20 NA
5 name1 method2 25 37.55
The difference between ifelse and if_else is that (from ?if_else
)
compared to the base ifelse(), this function is more strict. It checks that true and false are the same type. This strictness makes the output type more predictable, and makes it somewhat faster.
It also makes it less flexible.
If you have many of these conditions, you should use case_when()
as @SamR mentioned.
mutate(df, new_column = case_when(
Methods=="method2"& Names=="name1"~ 0.05 Amount * 1.5,
Names=="name2"~ 0.05 Amount * 1.5,
TRUE ~ NA_real_
))
Names Methods Amount new_column
1 name1 method1 5 7.55
2 name2 method2 10 15.05
3 name3 method2 15 22.55
4 name4 method1 20 NA
5 name1 method2 25 37.55