I have the following dataframe and I want to mutate all the columns in ENV
dataframe to substitute some value with case_when
function:
metrics <-
structure(list(var = c("SST", "SSS"), min = c(-1.82623172259469,
0.0106425614590989), max = c(30.7357019713913, 62.4178951570953
), Q1 = c(29.6467844102333, 37.2283509056568), Q2 = c(25.0978897764037,
35.1366150711973), Q3 = c(1.08054073780591, 33.6817701728394),
Q4 = c(-1.75609879755353, 22.3324745864139), slope.L = c(-0.219833625638,
-0.478071840394898), slope.R = c(0.352529811255446, 0.0881111953059067
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))
ENV1<-
structure(list(SST = c(-1.18181673490857, -1.29487169195505,
-1.2891296530063, -1.16459061806231, -1.02749131873705, -0.877831755030538,
-0.827006290249864, -0.87501492439503, -0.907842479642887, -0.925488955993432,
-0.928734689365441), SSS = c(34.4828464105725, 34.4536828344067,
34.4394813115398, 34.4402418419719, 34.4202143674095, 34.3793988878528,
34.3479811742902, 34.3259612267216, 34.2944239596526, 34.2533693730831,
34.225624174873)), row.names = 30:40, class = "data.frame")
ENV1 |> mutate_all(funs(
case_when(
. < metrics[metrics$var == x,]$Q1 ~ 0,
. <= metrics[metrics$var == x,]$Q3 ~ 1,
. > metrics[metrics$var == x,]$Q4 ~ 0
)
))
I have the issue with what to put instead of x
? I tried using names(.)
, a name of a column ( so it takes a value from a metrics
dataframe. But it does not work. I also tried colnames(.), vars(.), as.character(.) - with no luck
CodePudding user response:
Try cur_column()
ENV1 %>%
mutate(across(everything(),
~case_when(
. < metrics[metrics$var == cur_column(),]$Q1 ~ 0,
. <= metrics[metrics$var == cur_column(),]$Q3 ~ 1,
. > metrics[metrics$var == cur_column(),]$Q4 ~ 0
)
))