replace_column: Replace data frame column

View source: R/replace_column.R

replace_columnR Documentation

Replace data frame column

Description

Replaces the column of a data frame with that from a mask data frame.

Usage

replace_column(
  data,
  mask,
  ...,
  drop.extra = FALSE,
  ignore.ambiguous.match = FALSE
)

replace_column_(
  data,
  mask,
  old_column,
  match_column,
  new_column,
  drop.extra = FALSE,
  ignore.ambiguous.match = FALSE
)

Arguments

data

A data frame or a quitte object.

mask

A data frame containing the match_column and the new_column.

...

Definition of old, match, and new columns, see details.

drop.extra

Drop rows not present in match column?

ignore.ambiguous.match

replace_column() will issue a warning if the match column in mask does not map unambiguously to data, unless it is suppressed (TRUE). Using ambiguous matches can be desired for duplicating specific rows.

old_column

old column name, see details.

match_column

match column name, see details.

new_column

new column name, see details.

Details

Replaces the old column in data frame data by the new column from data frame mask based on the matching between old (data) and match (mask) columns.

This can be used to replace columns based on a mapping to, e.g., rename scenarios, regions, etc. in model data.

Value

A data frame or a quitte object, same as data.

Author(s)

Michaja Pehl

Examples

# simple example with matching old and match column names
(model_data <- data.frame(
    model  = c('Model1', '2ndModel', 'Model Three'),
    region = c('Region 1', 'Region 2', 'Region 1'),
    value  = 1:3))

(mask <- data.frame(
    model  = c('Model1', '2ndModel', 'Model Three', 'fourth Model'),
    clear_name = paste('Model', 1:4)))

replace_column(model_data, mask, model, clear_name)

# mismatched column names
(model_data <- data.frame(
    model  = c('Model1', '2ndModel', 'Model Three', 'fourth Model'),
    region = c('Region 1', 'Region 2', 'Region 1', 'Region 2'),
    value  = 1:4))

(mask <- data.frame(
    ugly_name  = c('Model1', '2ndModel', 'Model Three'),
    clear_name = paste('Model', 1:3)))

replace_column(model_data, mask, model = ugly_name, clear_name)

# SE example
replace_column_(model_data, mask, 'model', 'ugly_name', 'clear_name')

# dropping the extra entries in model
replace_column(model_data, mask, model = ugly_name, clear_name,
               drop.extra = TRUE)

# also works on quitte objects
require(dplyr)
(quitte <- tibble(
    model    = c('Model1', '2ndModel'),
    scenario = 'Scenario',
    region   = 'Region',
    variable = 'Variable',
    unit     = 'Unit',
    period   = 2010,
    value    = 1:2) %>%
        as.quitte())
replace_column(quitte, mask, model = ugly_name, clear_name)
str(.Last.value)


pik-piam/quitte documentation built on April 26, 2024, 12:58 a.m.