Median for multiple columns start Start_With same letters?

Viewed 89

I want to calculate the medeian for several columns based on what letters each column begins with, creating a new column.

I know the way to do this for mean using dplyr and an example like that shown below:

library(dplyr)
mutate(df, IVMean = rowMeans(select(df, starts_with("IV")), na.rm = TRUE))

But how is this possible for median?

I have tried a number of ways including select then mutate but having no luck.

1 Answers

We could use rowMedians after converting to matrix

library(matrixStats)
library(dplyr)
mutate(df, IVMedian = rowMedians(as.matrix(select(df, 
         starts_with("IV"))), na.rm = TRUE))

-ouptut

   IV1 IV2 IV3 col4 IVMedian
1   2   4   1    1        2
2   3   8   3    2        3
3   4   9   4    3        4

Or this can be done in rowwise with c_across

df %>%
    rowwise %>% 
    mutate(IVMedian = median(c_across(starts_with('IV')))) %>% 
    ungroup
# A tibble: 3 x 5
    IV1   IV2   IV3  col4 IVMedian
  <dbl> <dbl> <dbl> <dbl>    <dbl>
1     2     4     1     1        2
2     3     8     3     2        3
3     4     9     4     3        4

Or use pmap (from purrr)

library(purrr)
df %>%
    mutate(IVMedian = pmap_dbl(select(., starts_with('IV')), 
           ~ median(c(...))))
  IV1 IV2 IV3 col4 IVMedian
1   2   4   1    1        2
2   3   8   3    2        3
3   4   9   4    3        4

Or in collapse

library(collapse)
df$IVMedian <-  dapply(gvr(df, vars = '^IV'), MARGIN = 1, FUN = fmedian)

data

df <- data.frame(IV1 = c(2, 3, 4), IV2 = c(4, 8, 9), 
   IV3 = c(1, 3, 4), col4 = c(1, 2, 3))
Related