Learn R Programming

tidycells

Read Tabular Data from Diverse Sources and Easily Make Them Tidy

Author

Indranil Gayen

TL;DR

Given a file_name which is a path of a file that contains table(s). Run this read_cells() in the R-console to see whether support is present for the file type. If support is present, just run

read_cells(file_name)

Note

  • Just start with a small file, as heuristic-algorithm are not well-optimized (yet).
  • If the target table has numerical values as data and text as their attribute (identifier of the data elements), straight forward method is sufficient in the majority of situations. Otherwise, you may need to utilize other functions.

A Word of Warning :

Many functions in this package are heuristic-algorithm based. Thus, outcomes may be unexpected. I recommend you to try read_cells on the target file. If the outcome is what you are expecting, it is fine. If not try again with read_cells(file_name, at_level = "compose"). If after that also the output is not as expected then other functions are required to be used. At that time start again with read_cells(file_name, at_level = "make_cells") and proceed to further functions.

Introduction

The package provides utilities to read, cells from complex tabular data and heuristic detection based ‘structural assignment’ of those cells to a columnar or tidy format.

Read functionality has the ability to read (in a unified manner) structured, partially structured or unstructured tabular data (usually spreadsheets for public data dissemination and aimed for common human understanding) from various types of documents. The tabular information is read as cells. The ‘structure assignment’ functionality has both supervised and unsupervised way of assigning cells data to columnar/tidy format. Multiple disconnected blocks of tables in a single sheet are also handled appropriately.

These tools are suitable for unattended conversation of (maybe a pile of) messy tables (like government data) into a consumable format(usable for further analysis and data wrangling).

Installation

Install the CRAN version:

install.packages("tidycells")

To install the development version from GitHub you’ll need remotes package in R (comes with devtools). Assuming you have remotes you can install this package in R with the following command:

# devtools::install_github is actually remotes::install_github
remotes::install_github("r-rudra/tidycells")

To start with tidycells, I invite you to see vignette("tidycells-intro") or check out tidycells-website (to see vignette you need to install the package with vignette. That can be done in above command (remotes::install_github) by specifying build_vignettes = TRUE. Note that, it might be time consuming. CRAN version comes with prebuilt-vignette).

Quick Overview

Let’s take a quick look at an example data as given in

system.file("extdata", "marks.xlsx", package = "tidycells", mustWork = TRUE)

The data looks like (in excel)

Let’s try tidycells functions in this data

Read at once

# you should have tidyxl installed
system.file("extdata", "marks.xlsx", package = "tidycells", mustWork = TRUE) %>% 
  read_cells()
collated_1collated_2collated_3collated_4collated_5table_tagvalue
ScoreMaleSchool AStudent NameUtsyo RoySheet195
ScoreMaleSchool AStudent NameNakshatra GayenSheet199
ScoreFemaleSchool AStudent NameTitas GuptaSheet189
ScoreFemaleSchool AStudent NameUjjaini GayenSheet1100
ScoreMaleSchool BStudentIndranil GayenSheet170
ScoreMaleSchool BStudentS GayenSheet175
ScoreFemaleSchool BStudentSarmistha SenapatiSheet181
ScoreFemaleSchool BStudentShtuti RoySheet190
ScoreMaleSchool CNameI RoySheet150
ScoreMaleSchool CNameS GhoshSheet159
ScoreFemaleSchool CNameS SenapatiSheet161
ScoreFemaleSchool CNameU GuptaSheet138

The function read_cells is a set of ordered operations connected together. The flowchart of read_cells:

Let’s understand step by step procedures followed by read_cells.

# if you have tidyxl installed
d <- system.file("extdata", "marks.xlsx", package = "tidycells", mustWork = TRUE) %>% 
  read_cells(at_level = "make_cells") %>% 
  .[[1]]

Or

# or you may do
d <- system.file("extdata", "marks_cells.rds", package = "tidycells", mustWork = TRUE) %>% 
  readRDS()

Then

d <- numeric_values_classifier(d)
da <- analyze_cells(d)

After this you need to run compose_cells (with argument print_attribute_overview = TRUE)

dc <- compose_cells(da, print_attribute_overview = TRUE)

If you want a well-aligned columns then you may like to do

# bit tricky and tedious unless you do print_attribute_overview = TRUE in above line
dcfine <- dc %>% 
  dplyr::mutate(name = dplyr::case_when(
    data_block == 1 ~ major_row_left_2_1,
    data_block == 2 ~ major_col_bottom_1_1,
    data_block == 3 ~ major_row_left_1_1
  ),
  sex = dplyr::case_when(
    data_block == 1 ~ major_row_left_1_1,
    data_block == 2 ~ major_col_bottom_2_1,
    data_block == 3 ~ minor_row_right_1_1
  ),
  school = dplyr::case_when(
    data_block == 1 ~ minor_col_top_1_1,
    data_block == 2 ~ minor_corner_topLeft_1_1,
    data_block == 3 ~ minor_col_top_1_1
  )) %>% 
  dplyr::select(school,sex, name, value)

head(dcfine) looks like

schoolsexnamevalue
School AMaleUtsyo Roy95
School AMaleNakshatra Gayen99
School AFemaleTitas Gupta89
School AFemaleUjjaini Gayen100
School BMaleIndranil Gayen70
School BMaleS Gayen75

This is still not good right! You had to manually pick some weird column-names and spent some time and energy (when it was evident from data which columns should be aligned with whom).

The collate_columns functions does exactly this for you. So instead of manually picking column-names after compose cells you can simply run

# collate_columns(dc) should be same with 
# direct read_cells() result except table_tag column
collate_columns(dc) %>% 
  head()
collated_1collated_2collated_3collated_4collated_5value
ScoreMaleSchool AStudent NameUtsyo Roy95
ScoreMaleSchool AStudent NameNakshatra Gayen99
ScoreFemaleSchool AStudent NameTitas Gupta89
ScoreFemaleSchool AStudent NameUjjaini Gayen100
ScoreMaleSchool BStudentIndranil Gayen70
ScoreMaleSchool BStudentS Gayen75

Looks like staged example! Yes, you are right this is not always perfect (same is true for analyze_cells also). However, if the data is somehow helpful in demystifying underlying columns structure (like this one), then this will be useful.

These functions read_cells (all functionalities combined), analyze_cells, collate_columns are here to ease your pain in data wrangling and reading from various sources. It may not be full-proof solution to all types of tabular data. It is always recommended to perform these tasks manually whenever expected results are not coming.

Plots and Interactive Modules

The package provides ggplot based plots and shiny based interactive visualisations for understanding how the heuristic is functioning and also provides object (like cell-df or cell-analysis) editing capabilities.

The shiny package is required for interactive modules. Most of the features are self-explanatory and guided.

Check out interactive documentation of any of these functions listed below. All of these functions are available as RStudio Addins.

Here are screenshots of each interactive widgets.

  1. Plot tune (part of all modules)
  2. visual_crop() for data crop and deletion of sections
  1. visual_va_classify() for interactive VA classification
  2. visual_data_block_inspection() this shows how the heuristic has performed the analysis after analyze_cells
  1. visual_orientation_modification() for modification to heuristic based results
  2. visual_traceback() this is for observing how the original data is composed to form the final output. (compose_cells is called internally)

For each of these modules, there is a dynamic plot option available from plotly. If you have that package, the corresponding tab will be activated. Since all of these modules are entirely optional the dependency is kept at tidycells ‘suggests’ level only.

Reference and Related Projects

  • tidyxl: Read Untidy Excel Files: Imports non-tabular from Excel files into R. Exposes cell content, position and formatting in a tidy structure for further manipulation. Tokenizes Excel formulas. Supports ‘.xlsx’ and ‘.xlsm’ via the embedded ‘RapidXML’ C++ library http://rapidxml.sourceforge.net. Does not support ‘.xlsb’ or ‘.xls’.
  • unpivotr: Unpivot Complex and Irregular Data Layouts Tools for converting data from complex or irregular layouts to a columnar structure. For example, tables with multilevel column or row headers, or spreadsheets. Header and data cells are selected by their contents and position, as well as formatting and comments where available, and are associated with one other by their proximity in given directions. Functions for data frames and HTML tables are provided. Major parts of the package right now fully depend on unpivotr. The tidycells package would have never existed without this wonderful package from Duncan Garmonsway.
  • The rsheets project: It hosts several R packages (few of them are in CRAN already) which are in the early stages of importing spreadsheets from Excel and Google Sheets into R. Specifically, have a look at these projects which seems closely related to these projects : jailbreaker, rexcel (README of this project has a wonderful reference for excel integration with R).
  • readabs: Download and Tidy Time Series Data from the Australian Bureau of Statistics The readabs package helps you easily download, import, and tidy time series data from the Australian Bureau of Statistics from within R. This saves you time manually downloading and tediously tidying time series data and allows you to spend more time on your analysis.
  • ezpickr: Easy Data Import Using GUI File Picker and Seamless Communication Between an Excel and R Gives ability for choosing any rectangular data file using interactive GUI dialog box, and seamlessly manipulating tidy data between an ‘Excel’ window and R session.
  • The tidyABS package: The tidyABS package converts ABS excel tables to tidy data frames. It uses rules-of-thumb to determine the structure of excel tables, however it sometimes requires pointers from the user. This package is in early development.
  • The hypoparsr package: This package takes a different approach to CSV parsing by creating different parsing hypotheses for a given file and ranking them based on data quality features.

Acknowledgement

This package incomplete without following packages (apart from the unpivotr which is the core package on which tidycells depends largely, as mentioned above). Each of these packages are in suggests fields of tidycells. (The read_cells basically, performs unification on several functions from various packages to give you support for different file types. These are listed below.)

  • readr: for csv (in melted format)
  • readxl: for reading xls (if xlsx is present by default xlsx will be used for xls)
  • xlsx: for reading xls (also it has capabilities to read xlsx)
  • tidyxl: really fast library for reading xlsx
  • docxtractr : for docx and doc (it has a system level dependency now)
  • tabulizer : for pdf
  • XML : for html/xml type files
  • stringdist : for enhanced string matching in tidycells::collate_columns

Copy Link

Version

Install

install.packages('tidycells')

Monthly Downloads

10

Version

0.2.2

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Indranil Gayen

Last Published

January 9th, 2020

Functions in tidycells (0.2.2)

as_cell_df

Transform data into Cell-DF Structure
basic_classifier

Naive data_type Based Value/Attribute Classifier
read_cells

Read Cells from file
read_cell_part-class

read_cell_part class
compose_cells

Compose a Cell Analysis to a tidy form
get_group_id

Get Group ID for joined cells
value_attribute_classify

Value/Attribute Classifier
cell_analysis-class

cell_analysis class
visual_crop

Interactive operations and Visualizations
get_direction

get optimal direction (in terms of unpivotr directions)
get_direction_df

Get Directional Orientation for Attributes corresponding to a given data group
cell_composition_traceback

Display static composition traceback plot
get_unpivotr_direction_names

get unpivotr direction names
sample_based_classifier

Sample Based Value/Attribute Classifier
get_direction_metric

get direction metric
analyze_cells

Analyze Cells
numeric_values_classifier

Value/Attribute Classifier which considers number like cells as values
cell_df-class

cell_df class
analyse_cells

Analyse Cells
read_cells.read_cell_part

Read Cells from file
collate_columns

Collate Columns Based on Content
validate_cells

Validate cell-DF
%>%

Pipe operator
tidycells-package

tidycells package