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]])
There are several ways to check data type in R. We can make use of the “typeof()” function, “class()” function and even the “str()” function to check the data type of an entire dataframe.
enframe() converts named atomic vectors or lists to one- or two-column data frames. For a list, the result will be a nested tibble with a column of type list . For unnamed vectors, the natural sequence is used as name column.
To convert a column to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that returns a numeric value or converts any value to a numeric value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With