Search code examples
rdplyrmultiple-conditions

Mutate across with 2 conditions, one on variable name and the second on variable type


Let say I have the following table:

df <- data.frame(
  a1 = 1:5,
  b1 = as.character(1:5),
  c  = 1:5 
)

> df
  a1 b1 c
1  1  1 1
2  2  2 2
3  3  3 3
4  4  4 4
5  5  5 5

I would like to modify columns which name ends with "1" and which are numerical (meaning, only a1 and not c). I'm trying to ask this double condition in a mutate(across(where... without success. The condition regarding the columns' name is excluded.

The following script modifies both a1 and c.

df %>% 
  mutate(
    across(
      where(~ ends_with('1') && is.numeric(.)),
       ~ .x * 2
    ))

Solution

  • You don't need to use where() for name-testing functions like ends_with(). You can use

    
    df %>% 
      mutate(
        across(
          ends_with('1') & where(is.numeric),
          ~ .x * 2
      ))
    #   a1 b1 c
    # 1  1  1 1
    # 2  2  2 2
    # 3  3  3 3
    # 4  4  4 4
    # 5  5  5 5
    

    Also be careful with &&, it is only used for length-1 inputs, you need to use & for vectorization.