Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

type_convert

Re-convert character columns in existing data frame


Description

This is useful if you need to do some manual munging - you can read the columns in as character, clean it up with (e.g.) regular expressions and then let readr take another stab at parsing it. The name is a homage to the base utils::type.convert().

Usage

type_convert(
  df,
  col_types = NULL,
  na = c("", "NA"),
  trim_ws = TRUE,
  locale = default_locale()
)

Arguments

df

A data frame.

col_types

One of NULL, a cols() specification, or a string. See vignette("readr") for more details.

If NULL, column types will be imputed using all rows.

na

Character vector of strings to interpret as missing values. Set this option to character() to indicate no missing values.

trim_ws

Should leading and trailing whitespace be trimmed from each field before parsing it?

locale

The locale controls defaults that vary from place to place. The default locale is US-centric (like R), but you can use locale() to create your own locale that controls things like the default time zone, encoding, decimal mark, big mark, and day/month names.

Note

type_convert() removes a 'spec' attribute, because it likely modifies the column data types. (see spec() for more information about column specifications).

Examples

df <- data.frame(
  x = as.character(runif(10)),
  y = as.character(sample(10)),
  stringsAsFactors = FALSE
)
str(df)
str(type_convert(df))

df <- data.frame(x = c("NA", "10"), stringsAsFactors = FALSE)
str(type_convert(df))

# Type convert can be used to infer types from an entire dataset

# first read the data as character
data <- read_csv(readr_example("mtcars.csv"),
                 col_types = cols(.default = col_character()))
str(data)
# Then convert it with type_convert
type_convert(data)

readr

Read Rectangular Text Data

v1.4.0
GPL (>= 2) | file LICENSE
Authors
Hadley Wickham [aut], Jim Hester [aut, cre], Romain Francois [ctb], R Core Team [ctb] (Date time code adapted from R), RStudio [cph, fnd], Jukka Jylänki [ctb, cph] (grisu3 implementation), Mikkel Jørgensen [ctb, cph] (grisu3 implementation)
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.