help with mutate_at


I would like to change the datatypes of a bunch of variables from character to numeric and was trying to use the following for variables 4 all the way to 21:

df <- df%>%
  mutate_at(vars(4:21), ~(as.numeric))

and I get the following error:
Error: Problem with mutate() input ACT 2008. x Input ACT 2008 must be a vector, not a primitive function. i Input ACT 2008 is (structure(function (..., .x = ..1, .y = ..2, . = ..1) ....

Then I tried the following - it doesn't show any error. but the datatype is not changed. Some of the variables start with ACT and some with FC like ACT 2008 and FC 2020:

df <- df%>%
 mutate_at(vars(contains("ACT|FC")), ~(as.numeric))

How can I change several of these variables to numeric?

Thanks for your help!

I think you can do it like this.

df <- df%>%
 mutate_at(matches("ACT|FC"), as.numeric)

Thanks @woodward! But this gives the below error:
Error: matches() must be used within a selecting function. i See

I did look at the usage on the above link, but cannot figure out the right usage without getting error

Sorry, you are right.


df <- tibble(ACT2008 = "1", FC2020 = "2", A = "3")

  mutate_at(vars(matches("^ACT|^FC")), as.numeric)
#> # A tibble: 1 x 3
#>   ACT2008 FC2020 A    
#>     <dbl>  <dbl> <chr>
#> 1       1      2 3

Created on 2020-07-15 by the reprex package (v0.3.0)

Perfect! Thanks @woodward!
This works!

1 Like

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