SteveS
SteveS

Reputation: 4040

Automatically convert to the right class when building a data.table object in R?

I am frequently building some count stats using table.

My intention is to build a simple data.table / data_frame / tibble with 2 columns.

Here is an example:

tbl <- structure(c(61L, 66L, 114L, 72L, 127L, 45L, 66L, 67L, 70L), .Dim = 9L, .Dimnames = structure(list(
    c("1", "2", "3", "4", "5", "6", "7", "8", "9")), .Names = ""), class = "table")

What I do is data.table(df) %>% mutate(V1 = as.integer(V1))

Is there any option within data.table / data_frame to "convert" to the "right" class? You have this in the separate function (convert = TRUE).

Please advise.

Upvotes: 0

Views: 69

Answers (1)

Zygmunt Zawadzki
Zygmunt Zawadzki

Reputation: 251

There's a function in readr called parse_guess, which tries to "guess" the right type. The easiest solution is to use mutate_all to convert all column to the right class:

library(data.table)
library(dplyr)
tbl <- structure(c(61L, 66L, 114L, 72L, 127L, 45L, 66L, 67L, 70L), .Dim = 9L, .Dimnames = structure(list(
  c("1", "2", "3", "4", "5", "6", "7", "8", "9")), .Names = ""), class = "table")


res <- data.table(tbl) %>% mutate_all(readr::parse_guess)
glimpse(res)

Upvotes: 1

Related Questions