I want to create a new variable when two variables match a condition. In that case I want to have the smaller of two other variables. In my real data these are dates and I want to add other conditions in the case_when function, but I keep it simple her.
When I use first(sort(c(var1,var2))) the variables are interpreted as the whole column and it results in the smallest value for var1, var2 for the entire data.frame. But I want the smallest of the two variables per row in the data. In contrast, when I use var1 * var2 the variables per row in the data are used.
I tried the following:
library(dplyr)
starwars %>%
mutate(
new_var =
case_when(
hair_color == "brown" & eye_color == "brown" ~ first(sort(c(birth_year, mass)))
),
new_var2 =
case_when(
hair_color == "brown" & eye_color == "brown" ~ birth_year * mass
)
) %>%
select ( name, hair_color, eye_color, mass, birth_year, new_var, new_var2) %>%
filter(hair_color == "brown" & eye_color == "brown")
shortend output:
# A tibble: 9 × 7
name hair_color eye_color mass birth_year new_var new_var2
<chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Leia Organa brown brown 49 19 8 931
2 Han Solo brown brown 80 29 8 2320
3 Arvel Crynyd brown brown NA NA 8 NA
4 Wicket Systri Warrick brown brown 20 8 8 160
Thanks a lot in advance