Learn R Programming

replyr (version 0.3.01)

replyr_mapRestrictCols: Map names of columns to known values and drop other columns.

Description

Used to restrict a data item's column names and re-name them in bulk. Note: this can be expensive operation. Except for identity assigments keys and destinations must be disjoint.

Usage

replyr_mapRestrictCols(x, nmap, reverse = FALSE)

Arguments

x

data item to work on

nmap

named list mapping desired column names to column names in x. Doesn't support permutations of names.

reverse

logical if true apply the inverse of nmap intead of nmap.

Value

data item with columns limited down to those named as nmap values, and re-named from their orignal names (nmap values) to desired names (nmap keys).

Details

Something like replyr::replyr_mapRestrictCols is only useful to get control of a function that is not parameterized (in the sense it has hard-coded column names inside its implementation that don't the match column names in our data).

See Also

let

Examples

Run this code

# an external function with hard-coded column names
DecreaseRankColumnByOne <- function(d) {
  d$RankColumn <- d$RankColumn - 1
  d
}

# our example data, with different column names
d <- data.frame(Sepal_Length=c(5.8,5.7),
                Sepal_Width=c(4.0,4.4),
                Species='setosa',rank=c(1,2))
print(d)

# map our data to expected column names so we can use function
nmap <- c(GroupColumn='Species',
          ValueColumn='Sepal_Length',
          RankColumn='rank')
print(nmap)
dm <- replyr_mapRestrictCols(d,nmap)
print(dm)

# can now apply code that expects hard-coded names.
dm <- DecreaseRankColumnByOne(dm)

# map back to our original column names (for the columns we retained)
# Note: can only map back columns that were retained in first mapping.
replyr_mapRestrictCols(dm, nmap, reverse=TRUE)

Run the code above in your browser using DataLab