Home > OS >  dplyr across with matches() Error: Problem with `mutate()` input `..1` 1` must be a vector, not a fu
dplyr across with matches() Error: Problem with `mutate()` input `..1` 1` must be a vector, not a fu

Time:10-12

A data frame:

library(scales)
library(tidyverse)

mydf <- data.frame(
  x = 1:3,
  a_pct = c(0.3, 0.2, 0.1),
  y = letters[1:3],
  b_pct = c(0.5, 0.6, 0.7)
)

I would like to mutate those fields where the name contains string '_pct'. Tried:

mydf %>% mutate(across(matches('_pct'), ~percent))

Gives error:

Error: Problem with `mutate()` input `..1`.
ℹ `..1 = across(matches("_pct"), ~percent)`.
x `..1` must be a vector, not a function.

Can I use matches() with across() in this way?

CodePudding user response:

If we are using lamdba (~ or in base R function(x)) have to invoke it

mydf %>%
   mutate(across(matches('_pct'), ~percent(.)))
  x a_pct y b_pct
1 1   30% a   50%
2 2   20% b   60%
3 3   10% c   70%

or simply call without the lambda expression

mydf %>% 
   mutate(across(matches('_pct'), percent))
  x a_pct y b_pct
1 1   30% a   50%
2 2   20% b   60%
3 3   10% c   70%

CodePudding user response:

We could use contains:

library(dplyr)
mydf %>% 
  mutate(across(contains("_pct"), percent))
  x a_pct y b_pct
1 1   30% a   50%
2 2   20% b   60%
3 3   10% c   70%
  • Related