SiH
SiH

Reputation: 1546

How do I convert numbers (in char) to numbers (in numeric) using tidyverse

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")
)

Upvotes: 0

Views: 1803

Answers (2)

Onyambu
Onyambu

Reputation: 79208

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

Upvotes: 1

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

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

Upvotes: 2

Related Questions