dplyr::mutate_at() applied to columns of similar name

Below is reprex.

Wondering if #tidyeval gurus out there can find an equivalent solution with dplyr::mutate_at() .

I attempted solutions suggested by @cderv in issue #20562, but no luck this time as there are multiple columns.

Look forward to enlightenment.

Thanks!

library(tidyverse)

tibble::tribble(
~wht.x, ~wht.y, ~whp.x,  ~whp.y, ~group_id,
 NaN,    575,    NaN,  478.18,        1L,
 NaN,  547.6,    NaN,    1021,        2L,
 NaN,  547.6,    NaN, 1021.24,        3L,
 NaN,  547.6,    NaN,  948.64,        4L,
 NaN,  544.2,    NaN,  994.02,        5L,
 NaN,  544.7,    NaN,  997.24,        6L
) -> data

# desired outcome
data %>% 
  mutate(whp.x = coalesce(whp.x, whp.y),
         wht.x = coalesce(wht.x, wht.y))
#> # A tibble: 6 x 5
#>   wht.x wht.y whp.x whp.y group_id
#>   <dbl> <dbl> <dbl> <dbl>    <int>
#> 1  575   575   478.  478.        1
#> 2  548.  548. 1021  1021         2
#> 3  548.  548. 1021. 1021.        3
#> 4  548.  548.  949.  949.        4
#> 5  544.  544.  994.  994.        5
#> 6  545.  545.  997.  997.        6

This is one solution, courtesy of @cderv (#21583).

data %>% 
  gather(key, value, -group_id) %>% 
  mutate(key = str_extract(key, '.*(?=\\.)')) %>% 
  ungroup() %>% 
  group_by(group_id, key) %>% 
  summarise_if(is.numeric, mean, na.rm = TRUE) %>% 
  spread(key, value)
#> # A tibble: 6 x 3
#> # Groups:   group_id [6]
#>   group_id   whp   wht
#>      <int> <dbl> <dbl>
#> 1        1  478.  575 
#> 2        2 1021   548.
#> 3        3 1021.  548.
#> 4        4  949.  548.
#> 5        5  994.  544.
#> 6        6  997.  545.
2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.