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