tidyr::parse_number() across variables where is.character

# A tibble: 5 x 5
   code name  v1          v2            v3
  <int> <chr> <chr>       <chr>      <int>
1     1 A     201,000.2   100            2
2     2 B     100         701,000.2      3
3     3 C     2           2              4
4     4 D     1,262,004.5 300            5
5     5 E     300         523,200.45     6

In the example above , how can I apply tidyr::parse_number() across the columns v1:v3 . Note that in my actual data set (obtained via web scraping) v1:v3 either appear as character or numeric. So, I want to apply parse_number() to the character variables.

library(tidyverse)
# toy data
df <- tibble(
  code = 1:5,
  name = c("A", "B", "C", "D","E"),
  v1 = c("201,000.2", "100", "2", "1,262,004.5", "300"),
  v2 = c("100", "701,000.2", "2",  "300", "523,200.45"),
  v3 = c(2:6)
) 
# my attempt
df %>%
  mutate(across(where(is.character) & !c(code, name)), parse_number)
#> Error: Problem with `mutate()` input `..2`.
#> i `..2 = parse_number`.
#> x `..2` must be a vector, not a function.

Created on 2021-07-24 by the reprex package (v2.0.0)

Watch your brackets

df %>%
  mutate(across(where(is.character) & !c(code, name), parse_number))

Side note you load tidyverse, therefore you have access to parse_number, however it's from the readr package rather than tidyr.

1 Like

Thanks for pointing out my mistakes :blush:The problem is solved !

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.