The median of mpg is 19.2.
In the next line I would like to add this info (e.g. "19.2") to the new mutated column name "median_dich". So that at the end the new column name should be median_dich19.2
.
I know how to do it outside of this special situation. My question is to directly get the median value and paste it to the new mutated column name?
What I have tried so far:
#TRY 1
library(dplyr)
mtcars %>%
mutate(median_mpg = median(mpg)) %>%
mutate(glue("median_dich{median_mpg}") = ifelse(mpg > median_mpg, 1, 0))
#TRY 2
library(dplyr)
library(rlang)
mtcars %>%
mutate(median_mpg = median(mpg)) %>%
mutate(!!paste0("median_dich_", median_mpg) := ifelse(mpg > median_mpg, 1, 0))
#TRY 3
library(dplyr)
library(rlang)
library(glue)
mtcars %>%
mutate(median_mpg = median(mpg)) %>%
mutate(!!sym(glue("median_dich_{median_mpg}")) := ifelse(mpg > median_mpg, 1, 0))
A one-liner:
You can wrap
mpg > median(mpg)
inas.integer()
, but it makes little/no difference, and adds visual clutter, so I didn't.Here's a longer version, where we create the median_mpg column too:
Output (with relevant columns):
Note: I'm sure I don't need to tell you this TarJae, but putting data in your column names is bad practice- I can't think off the top of my head of a situation where it would be a good idea...so consider not doing it! ^^