下面是一个例子。共有三列,其中两列包含数字,但都是字符。
我希望使用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))
- 输出
# 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