Home > front end >  How do I convert numbers (in char) to numbers (in numeric) using tidyverse
How do I convert numbers (in char) to numbers (in numeric) using tidyverse

Time:08-06

Below is an example. There are three columns, two of them contain numbers but are in characters.

I wish to automatically convert numbers (in char) to numbers (in numeric) using tidyverse.

The actual data has 100s of columns with all in char, but it contains several columns which have values.

library(tidyverse)

tbl <- tibble(x = c("1", "2"),
              y = c("a", "b"),
              z = c("3", "4")
)

CodePudding user response:

We can use

tbl |> mutate(across(.fns = ~ if(all(!is.na(as.numeric(.x)))) as.numeric(.x) else .x))
  • output
# A tibble: 2 × 3
      x y         z
  <dbl> <chr> <dbl>
1     1 a         3
2     2 b         4

CodePudding user response:

type.convert(tbl, as.is =TRUE)

# A tibble: 2 x 3
      x y         z
  <int> <chr> <int>
1     1 a         3
2     2 b         4
  • Related