efficiently parse number then divide -- mutate(), across(), and parse_number()

In the example below, I first convert v1 and v2 to numeric type then divide each by 100. How can I do the same thing using just one line of code?

library(tidyverse)

# Toy Data
df <- tibble(
  name = c("John", "Michael", "Jessica"),
  gender = c("M", "M", "F"),
  v1 = as.character(c(100, 200, 300)),
  v2 = as.character(c(500, 600, 700))
)
df
#> # A tibble: 3 x 4
#>   name    gender v1    v2   
#>   <chr>   <chr>  <chr> <chr>
#> 1 John    M      100   500  
#> 2 Michael M      200   600  
#> 3 Jessica F      300   700
# parse number then divide by 100
df %>% 
  mutate(across(starts_with("v"), parse_number)) %>% 
  mutate(across(starts_with("v"), ~./100))
#> # A tibble: 3 x 4
#>   name    gender    v1    v2
#>   <chr>   <chr>  <dbl> <dbl>
#> 1 John    M          1     5
#> 2 Michael M          2     6
#> 3 Jessica F          3     7

Created on 2021-12-08 by the reprex package (v2.0.0)

Maybe not the most elegant, but this worked for me.

1 Like

@hdshea Many thanks!

This topic was automatically closed 7 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.