如何更改 tibble 的列数据类型(最少键入)

How to change column data type of a tibble (with least typing)

管道和 tidyverse 有时非常方便。用户想要将一列从一种类型转换为另一种类型。

像这样:

mtcars$qsec <-as.integer(mtcars$qsec)

这需要输入两次我需要的内容。请不要建议 "with" 命令,因为我发现它使用起来很混乱。

tidyverse 和 magrittr %<>% 以最少的输入量完成相同操作的方法是什么?另外,如果 qsec 是第 6 列,我怎么能仅仅参考列位置呢?类似(不正确的代码)

mtcars %<>% mutate(as.integer,qsec)
mtcars %<>% mutate(as.integer,[[6]])

只需输入一次该列的参考 - 符合要求的答案是

mtcars %<>% mutate_at(6, as.integer)

编辑:请注意,自 2021 年起,mutate_at 语法 has been superseded

mtcars %<>% mutate(across(6), as.integer)

要按名称引用列,一种冗余键入列名称的解决方案是

mtcars %<>% mutate(qsec = as.integer(qsec))

注意:感谢以上评论用户

这个解决方案可能是最短的:

mtcars$qsec %<>% as.integer

诀窍是直接在列上执行转换操作 > 不再需要 mutate()。

更新 dplyr 1.0.0

Tidyverse 建议使用 across() 替换,如@Aren Cambre 所述,mutate_at.

这是它的样子:

mtcars %>% mutate(across(qsec, as.integer))

重要:

注意as.integer写的时候没有括号()