25

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]])
user438383
  • 5,716
  • 8
  • 28
  • 43
userJT
  • 11,486
  • 20
  • 77
  • 88

3 Answers3

25

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

qix
  • 7,228
  • 1
  • 55
  • 65
userJT
  • 11,486
  • 20
  • 77
  • 88
16

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.

Agile Bean
  • 6,437
  • 1
  • 45
  • 53
9

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

Agile Bean
  • 6,437
  • 1
  • 45
  • 53