Reputation: 11934
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
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
Reputation: 7151
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))
Note that as.integer
is written without parentheses ()
Upvotes: 10
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