Home > other >  Tidyverse min{x, 1-x} by column
Tidyverse min{x, 1-x} by column

Time:06-16

My data is the following:

tibble(var1.q = 0.01, var2.q = .99, var3.q = .45) -> foo

I would like to calculate 2 * min{x, 1-x} for each column.

In base R, I could do

 2*apply(bind_rows(foo, 1-foo), 2, FUN=min)

but I struggle to find the tidyverse equivalent of this.

Expected result:

  0.02   0.02   0.90 

CodePudding user response:

We can use across(everything) to create summaries of each column and then define an anonymous function function(x) 2 * min(x, 1-x) to perform the summary calculation.

library(dplyr)
foo %>% summarise(across(everything(), function(x) 2 * min(x, 1-x)))
# A tibble: 1 × 3
  var1.q var2.q var3.q
   <dbl>  <dbl>  <dbl>
1   0.02 0.0200    0.9

CodePudding user response:

A possible solution, using pmin (parallel min) to calculate the min rowwise:

library(dplyr)

foo %>% 
  mutate(across(everything(), ~ 2 * pmin(.x, 1-.x) ))

#> # A tibble: 1 × 3
#>   var1.q var2.q var3.q
#>    <dbl>  <dbl>  <dbl>
#> 1   0.02 0.0200    0.9

CodePudding user response:

We can use pmin directly over foo and 1-foo

> 2 * pmin(foo, 1 - foo)
  var1.q var2.q var3.q
1   0.02   0.02    0.9
  • Related