set_types: Set data types of the columns in a data frame

Description Usage Arguments Value Examples

View source: R/set_names.R

Description

Set the data type of all columns in a data frame at the same time. This is similar to the 'set_names()' function from the purrr and rlang packages and is meant to work in a similar way. Instead of passing a vector of names, pass a vector of data types.

Usage

1
set_types(data, types = NULL)

Arguments

data

a data frame whose columns will potentially have their data types altered

types

a vector of data types aligning, in order, to the columns of the data frame. Currently supported data types are

  • character

  • integer

  • numeric

  • logical

  • date (from 'lubridate::as_date')

Value

If 'types' is NULL, the sama data frame is returned; otherwise, if 'types' is a vector of valid data types, the data frame is returned with the columns coerced to those data types.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
library(dplyr)
library(purrr)
library(lubridate)

char_vec  <- c("abcd", "1234", "hello", "world")
int_vec   <- c(1L, 2L, 3L, 4L)
num_vec   <- c(3.14, 10, 5.5, 0.12345)
logic_vec <- c(TRUE, FALSE, FALSE, NA)
date_vec  <- c(
    as_date("2020-01-01"),
    as_date("2000-01-01"),
    as_date("2005-08-31"),
    as_date("1969-07-04")
)

test_data <- tibble(
    char_col  = char_vec,
    int_col   = int_vec,
    num_col   = num_vec,
    logic_col = logic_vec,
    date_col  = date_vec
) %>% mutate_all(as.character)

test_data %>%
    set_names(c("characters", "integers", "numerics", "logicals", "dates")) %>%
    set_types(c("character", "integer", "numeric", "logical", "date"))

RobbyLankford/lankford documentation built on April 24, 2020, 7:37 p.m.