繁体   English   中英

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

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

下面是一个例子。 共有三列,其中两列包含数字,但都是字符。

我希望使用 tidyverse 自动将数字(字符)转换为数字(数字)。

实际数据有 100 多列,全部为 char,但它包含几列有值。

library(tidyverse)

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

我们可以用

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