简体   繁体   English

如何使用 tidyverse 将数字(char)转换为数字(数字)

[英]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.我希望使用 tidyverse 自动将数字(字符)转换为数字(数字)。

The actual data has 100s of columns with all in char, but it contains several columns which have values.实际数据有 100 多列,全部为 char,但它包含几列有值。

library(tidyverse)

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

We can use我们可以用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM