change.fieldnames: Change some or all of the colnames of a data.frame or matrix...

View source: R/change.fieldnames.R

change.fieldnamesR Documentation

Change some or all of the colnames of a data.frame or matrix via a 1-1 map

Description

Returns a new set of field names, based on the old set of names, which can be specified in a file or as parameters. This provides a convenient way to specify which names will be replaced with which new names, via a map of 1-1 relationships between the old names and new names.

Usage

change.fieldnames(allnames, oldnames, newnames, file = NA, sort = FALSE)

Arguments

allnames

Character vector, optional. A vector of all the original fieldnames, such as the results of names(mydataframe).

oldnames

Character vector, optional. A vector of only those original fieldnames that you want to change, in any order.

newnames

Character vector, optional. A vector of new names, sorted in an order corresponding to oldnames.

file

Character, optional. A filename (or path with filename) for a mapping file that is a csv file with two columns named with a header row: oldnames, newnames (instead of passing them to the function as parameters).

sort

Logical value, optional, FALSE by default. If FALSE, return new fieldnames. If sort=TRUE, return vector of indexes giving new position of given field, based on sort order of oldnames.

Details

This function returns a character vector of length equal to the number of oldnames (the parameter or the field in the file).

Value

A vector of character strings, the full set of fieldnames, with some or all updated if sort=FALSE (default). Uses oldnames and newnames, or file for mapping. If those are not specified, it tries to open an interactive window for editing a mapping table to create and save it as a csv file.

If sort=TRUE, return vector of indexes giving new position of given field, based on sort order of oldnames. If sort=TRUE, names in oldnames that are not in allnames are ignored with warning, & names in allnames that are left out of oldnames left out of new sort order indexes.

See Also

put.first() which make it easier to rearrange the order of columns in a data.frame.

Examples

oldnames <- c('PCTILE', 'REGION')
newnames <- c('percentile', 'usregion')
df <- data.frame(REGION=301:310, ID=1:10, PCTILE=101:110, OTHER=1:10)
names(df) <- change.fieldnames(names(df), oldnames, newnames); names(df)
names(df) <- change.fieldnames(names(df), "ID", "identification"); names(df)
# names(df) <- change.fieldnames(names(df)); names(df)  # does not work on MacOSX?
# names(df) <- change.fieldnames(names(df), 'saved fieldnames.csv'); names(df)
df[ change.fieldnames(names(df), c('ID', 'OTHER', 'REGION', 'PCTILE'), sort=TRUE)]
# much like df[ , c('ID', 'OTHER', 'REGION', 'PCTILE') ]
#  change.fieldnames is more useful when file specified

ejanalysis/analyze.stuff documentation built on April 2, 2024, 10:10 a.m.