spec_from_df: Create a cols specification from a dataframe.

Description Usage Arguments Details Value Examples

Description

Given a dataframe with columns named col_name and col_type, construct a cols specification.

Usage

1

Arguments

df

A dataframe with column names col_name and col_type.

Details

This allows one to create a cols specification from an existing dataframe. Executing types_df on a dataframe will return a new dataframe containing the column names and types needed to create a cols specification.

The inverse operation is spec_to_df.

Value

A cols specification.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
## create an artificial df
test_df <- readr::read_csv(paste0("a,b,c,d\n",
                                  "1,two,3.0,2016-05-01T11:40:44\n",
                                  "4,five,6.0,2014-12-01T06:12:23"))

## write the spec to disk as a mere CSV
spec_df <- spec_to_df(readr::spec(test_df))
tmp_dir <- tempdir()
readr::write_csv(spec_df,
                 file.path(tmp_dir, "test_df_spec.csv"))
readr::write_csv(test_df,
                 file.path(tmp_dir, "test_df.csv"))

## create a specification and then read original CSV back in
spec_df_from_csv <- readr::read_csv(file.path(tmp_dir, "test_df_spec.csv"))
spec_from_csv <- spec_from_df(spec_df_from_csv)
test_df_from_csv <- readr::read_csv(file.path(tmp_dir, "test_df.csv"),
                                    col_types = spec_from_csv)
## returns TRUE
assertthat::are_equal(test_df, test_df_from_csv)

curtisalexander/CRAmisc documentation built on May 14, 2019, 12:52 p.m.