Skip to contents

Converts columns to a given format.

Usage

cast_columns(
  df,
  cast_type,
  dfname = substitute(df),
  vec_name = substitute(cast_type)
)

Arguments

df

A dataframe containing the columns specified in the names of cast_type.

cast_type

A named list containing the name of the function to cast between types. The list's names are the names of the columns to cast in df. Elements of this list can be:

  • a character giving a valid function name to call

  • a list with the first element being the function to call (character) and additional arguments to the function call (that can be named as the names of the functions' arguments).

dfname

Name of the dataframe to display in the error message. It is useful when this function is used inside other functions for a better error message.

vec_name

Name of the vector of columns to display in the error message. It is useful when this function is used inside other functions for a better error message.

Value

the original dataframe with the specified columns casted with the type indicated in cast_type.

Examples

df <- data.frame(num = 1:10,
                 char = letters[1:10],
                 date = rep("12/24/2020", 10))
cast <- list(num = "as.character",
             char = "as.factor",
             date = list("as.Date", 
                         format = "%m/%d/%Y"))
dfcast <- cast_columns(df, cast)