Replaces the values of identifier columns (by default id and
item) with short ASCII codes such as P0001 and I0001.
This is useful when identifiers are in a script or use characters that are
awkward to type on a US keyboard, which makes subsetting, writing model
formulas, and reading wide-format column names difficult.
Usage
irw_recode(df, cols = c("id", "item"), prefix = NULL)Arguments
- df
A data frame in IRW long format.
- cols
Character vector of columns to recode. Defaults to
c("id", "item").- prefix
Optional named character vector overriding the default code prefixes, e.g.
c(item = "Q"). Defaults are"P"forid,"I"foritem, and the uppercased first letter of the column name otherwise.
Value
df with the requested columns replaced by character codes and
an "irw_recode_key" attribute holding a data frame with columns
column, original, and code.
Details
Codes are assigned in sorted order of the unique non-missing values of each column, so they are deterministic for a given set of values. They are, however, only meaningful relative to their key: two different subsets of the same table will generally not produce the same codes.
The mapping is attached to the result as an attribute and can be retrieved
with irw_recode_key(). Save it if you need it later, because most
base R operations on a data frame drop attributes. The original values can
be restored with irw_decode().
Note that recoding item breaks manual joins against
irw_itemtext() output, which is keyed on the original item
identifiers. Use irw_recode_key() to map back before joining.
Examples
df <- data.frame(
id = c("María-01", "María-01", "René-02"),
item = c("Q_alpha", "Q_beta", "Q_alpha"),
resp = c(1, 0, 1),
stringsAsFactors = FALSE
)
d <- irw_recode(df)
#> Recoded 'id': 2 unique values -> P0001..P0002
#> Recoded 'item': 2 unique values -> I0001..I0002
#> Save the mapping with irw_recode_key() if you need it later; most operations on a data frame drop attributes.
head(d)
#> id item resp
#> 1 P0001 I0001 1
#> 2 P0001 I0002 0
#> 3 P0002 I0001 1
irw_recode_key(d)
#> column original code
#> 1 id María-01 P0001
#> 2 id René-02 P0002
#> 3 item Q_alpha I0001
#> 4 item Q_beta I0002
identical(irw_decode(d)$item, df$item)
#> [1] TRUE