r:tidyverse: How to change column data type using pipes with least typing

userJT picture userJT · May 11, 2017 · Viewed 18.4k times · Source

Pipes and tidyverse are sometimes very convenient. The user wants to do convert one column from one type to another.

Like so:

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

This requires typing twice what I need. Please do not suggest "with" command since I find it confusing to use.

What would be the tidyverse and magrittr %<>% way of doing the same with least amount of typing? Also, if qsec is 6th column, how can I do it just refering to column position. Something like (not correct code)

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

Answer

userJT picture userJT · May 24, 2017

With typing reference to the column just once - the compliant answer is

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

To refer to column by name, solution with one redundant typing of column name is

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

NOTE:credit goes to commenting users above