Restrict a data item's column names and re-name them in bulk.

replyr_mapRestrictCols(x, nmap, ..., restrict = FALSE, reverse = FALSE)

Arguments

x

data item to work on

nmap

named list mapping with keys specifying new column names, and values as original column names.

...

force later arguments to bind by name

restrict

logical if TRUE restrict to columns mentioned in nmap.

reverse

logical if TRUE apply the inverse of nmap instead of nmap.

Value

data item with columns renamed (and possibly restricted).

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

Examples

# 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)
#> Sepal_Length Sepal_Width Species rank #> 1 5.8 4.0 setosa 1 #> 2 5.7 4.4 setosa 2
# map our data to expected column names so we can use function nmap <- c(GroupColumn='Species', ValueColumn='Sepal_Length', RankColumn='rank') print(nmap)
#> GroupColumn ValueColumn RankColumn #> "Species" "Sepal_Length" "rank"
dm <- replyr_mapRestrictCols(d,nmap) print(dm)
#> ValueColumn Sepal_Width GroupColumn RankColumn #> 1 5.8 4.0 setosa 1 #> 2 5.7 4.4 setosa 2
# 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)
#> Sepal_Length Sepal_Width Species rank #> 1 5.8 4.0 setosa 0 #> 2 5.7 4.4 setosa 1