knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
rlookup
to create a value map from a data frame.Attach and load rlookup
. The %>%
piping operator from magrittr
is strongly recommended.
library(rlookup) library(magrittr)
We are using the good old mtcars
data to illustrate the use of this package.
mtcars <- mtcars %>% tibble::rownames_to_column("model") head(mtcars)
We desire to recode cyl
, vs
, am
variables, which are respectively cylinder count, engine configuration, and transmission type.
A value map is called a lookup
in rlookup
; it is a data frame that has three columns: col_name
, old_value
and new_value
, containing respectively:
Use build_lookup()
function to select desired columns from a data frame to make a value map. The new_value
column is empty.
mtcars_lookup <- mtcars %>% build_lookup(cyl, vs, am) mtcars_lookup
Specify the path in write_lookup()
. Give file name a csv
suffix, as the output is in CSV format.
# Write the value map # mtcars_lookup %>% write_lookup("mtcars_lookup.csv") # Examine the file by reading it # read_lookup("mtcars_lookup.csv")
Edit the new_value
column using a spreadsheet program, such as OpenOffice Calc or Microsoft Excel; if unavailable, use a free CSV editor such as {Ron's Editor}[https://www.ronsplace.eu/Products/RonsEditor].
From your R session, edit_lookup()
is available to make a quick edit. If the funciton is supplied with a value map data frame, it will return the modified value map;If supplied with a file path to a value map file, modifications will be directly saved to the file. In both instances, the user will be asked to confirm the change.
You may delete value sets (rows) if you don't want to map them.
Do not try anything funny. As with many R programs, rlookup
is not designed to protect the user from himself.
# Let's pretend that you've made desired change to the `new_value`. read_lookup("mtcars_lookup_edited.csv") %>% write_lookup("mtcars_lookup.csv", overwrite = TRUE) read_lookup("mtcars_lookup.csv")
Now the value map is ready, finally it's time to replace values in the the data frame!
mtcars_recoded <- mtcars %>% use_lookup("mtcars_lookup.csv") mtcars_recoded
Every value in their corresponding column has changed. That's basically it!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.