Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change column data type of a tibble

Tags:

r

tidyverse

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]])
like image 920
userJT Avatar asked May 11 '17 14:05

userJT


People also ask

How do I find the data type of a column in R?

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.

What does Tibble :: Enframe () do?

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.

How do I change a character to a column in numeric in R?

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.


1 Answers

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

like image 68
userJT Avatar answered Sep 18 '22 03:09

userJT