R

Auto-detect R data frame column data types

Here is how to auto-detect and change data types for multiple columns in R at the same time.

My dataset looks like this.

df <- data.frame(
  Date  = c("-", "2019-12-02", "2019-12-03", "2019-12-04", "2019-12-05", "2019-12-06", "2019-12-07", "2019-12-08", "2019-12-09"),
  Values1 = c("-", "8", "7", "10", "13", "9", "12", "14", "11"),
  Values2 = c("-", "8", "9", "10", "13", "9", "17", "6", "11"), 
  stringsAsFactors=FALSE)

The first line contains unnecessary information, but even if I remove that, column data types stay the same.

df <- df[-1,]

There is an easy way to change that with type_convert function from the readr package.

df <- readr::type_convert(df)

If you want to know how to reflow your code or other useful RStudio tips and tricks, take a look at this post.

0 comments on “Auto-detect R data frame column data types

Leave a Reply

Your email address will not be published. Required fields are marked *