auto_melt {countries}R Documentation

Automatic pivoting of country and year columns to a long format

Description

When at least 3 country names or years are found in the column names, the function will automatically transform the table from a wide to a long format by pivoting the country/year columns. This is equivalent to applying tidyr::pivot_longer() or data.table::melt() on the columns with years or countries as names. The function is able to detect years also when they are preceded by a prefix.

Usage

auto_melt(
  x,
  names_to = "pivoted_colnames",
  values_to = "pivoted_data",
  verbose = TRUE,
  pivoting_info = FALSE
)

Arguments

x

A data.frame object to check and pivot country or year columns.

names_to

String indicating how the column holding the name of the pivoted columns should be called in the output table. Default is "pivoted_colnames"

values_to

String indicating how the column containing the values of the pivoted columns should be called in the output table. Default is "pivoted_data"

verbose

Logical value. If set to TRUE (the default), a message will be displayed on the console indicating which columns are being pivoted. If set to FALSE, the messages are turned off.

pivoting_info

Logical value indicating whether to return the list of names of the column that have been pivoted. Default is FALSE. If set to TRUE, the output will be a list instead of simple data.frame. Teh list will contain 1) the pivoted table, 2) the list of pivoted columns.

Value

A table transformed into a "long" format by pivoting country or year columns. If year columns are found, a numeric column called "year_pivoted_colnames" is added isolating the years extracted from the table header's.

See Also

auto_merge, find_countrycol,find_timecol

Examples

# example data
example <- data.frame(Date = c("01.01.2019", "01.02.2019", "01.03.2019"),
                      Japan = 1:3,
                      Norway = 2:4,
                      Germany = 3:5,
                      US = 4:6)
example2 <- data.frame(Sector = c("Agriculture", "Mining", "Forestry"),
                       X2000 = 1:3,
                       X2001 = 2:4,
                       X2002 = 3:5,
                       X2003 = 4:6)

# examples pivotting countries and years from column names
auto_melt(example)
auto_melt(example2)

[Package countries version 1.2.0 Index]