userJT
userJT

Reputation: 11934

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

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

Upvotes: 25

Views: 52579

Answers (3)

userJT
userJT

Reputation: 11934

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

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

Edit: note that as of 2021, mutate_at syntax has been superseded by

mtcars %<>% mutate(across(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

Upvotes: 26

Agile Bean
Agile Bean

Reputation: 7151

Update dplyr 1.0.0

Tidyverse recommends using across() which replaces, as noted by @Aren Cambre, mutate_at.

Here is how it looks like:

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

Important:

Note that as.integer is written without parentheses ()

Upvotes: 10

Agile Bean
Agile Bean

Reputation: 7151

This solution is probably the shortest:

mtcars$qsec %<>% as.integer

The trick is to perform the cast operation directly on the column > no need for mutate() any more.

Upvotes: 17

Related Questions