| Title: | Reproducible Open Coding Kit |
| Version: | 0.9.6 |
| Date: | 2025-06-11 |
| Maintainer: | Gjalt-Jorn Peters <rock@opens.science> |
| Description: | The Reproducible Open Coding Kit ('ROCK', and this package, 'rock') was developed to facilitate reproducible and open coding, specifically geared towards qualitative research methods. It was developed to be both human- and machine-readable, in the spirit of MarkDown and 'YAML'. The idea is that this makes it relatively easy to write other functions and packages to process 'ROCK' files. The 'rock' package contains functions for basic coding and analysis, such as collecting and showing coded fragments and prettifying sources, as well as a number of advanced analyses such as the Qualitative Network Approach and Qualitative/Unified Exploration of State Transitions. The 'ROCK' and this 'rock' package are described in the ROCK book (Zörgő & Peters, 2022;https://rockbook.org), in Zörgő & Peters (2024) <doi:10.1080/21642850.2022.2119144> and Peters, Zörgő and van der Maas (2022) <doi:10.31234/osf.io/cvf52>, and more information and tutorials are available athttps://rock.science. |
| BugReports: | https://codeberg.org/R-packages/rock/issues |
| URL: | https://rock.opens.science |
| License: | GPL-3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| RoxygenNote: | 7.3.2 |
| Depends: | R (≥ 4.1) |
| Imports: | data.tree (≥ 1.1.0), DiagrammeR (≥ 1.0.0), DiagrammeRsvg (≥0.1), ggplot2 (≥ 3.2.0), glue (≥ 1.3.0), htmltools (≥0.5.0), markdown (≥ 1.1), purrr (≥ 0.2.5), squids (≥25.5.3), yaml (≥ 2.2.0), yum (≥ 0.1.0) |
| Suggests: | covr, googlesheets4, haven (≥ 2.4), justifier (≥ 0.2),knitr, limonaid (≥ 25.5), openxlsx (≥ 4.2), pdftools, pkgdown(≥ 2.0.0), preregr (≥ 0.1.9), readxl, rmarkdown, rvest, rsvg,rstudioapi, striprtf, testthat, writexl, XLConnect, xml2, zip |
| VignetteBuilder: | knitr |
| NeedsCompilation: | no |
| Packaged: | 2025-06-11 16:47:32 UTC; Gjalt-Jorn Peters |
| Author: | Gjalt-Jorn Peters |
| Repository: | CRAN |
| Date/Publication: | 2025-06-13 20:00:06 UTC |
rock: A Reproducible Open Coding Kit
Description
This package implements an open standard for working withqualitative data, as such, it has two parts: a file format/conventionand this R package that facilitates working with .rock files.
The ROCK File Format
The.rock files are plain text files where a number of conventions are usedto add metadata. Normally these are the following conventions:
The smallest 'codeable unit' is called an utterance, and utterances are separated by newline characters (i.e. every line of the file is an utterance);
Codes are in between double square brackets:
[[code1]]and[[code2]];Hierarchy in inductive code trees can be indicated using the greater than sign (
>):[[parent1>child1]];Utterances can have unique identifiers called 'utterance identifiers' or 'UIDs', which are unique short alphanumeric strings placed in between double square brackets after 'uid:', e.g.
[[uid:73xk2q07]];Deductive code trees can be specified using YAML
Therock R Package Functions
The most important functions areparse_source() to parse one source andparse_sources()to parse multiple sources simultaneously.clean_source() andclean_sources() can be usedto clean sources, andprepend_ids_to_source() andprepend_ids_to_sources() can beused to quickly generate UIDs and prepend them to each utterance in a source.
For analysis,create_cooccurrence_matrix(),collapse_occurrences(), andcollect_coded_fragments() can be used.
Author(s)
Maintainer: Gjalt-Jorn Petersrock@opens.science (ORCID) [copyright holder]
Authors:
Szilvia Zörgő (ORCID)
See Also
Useful links:
Add HTML tags to a source
Description
This function adds HTML tags to a source to allow pretty printing/viewing.
Usage
add_html_tags( x, context = NULL, codeClass = rock::opts$get("codeClass"), codeValueClass = rock::opts$get("codeValueClass"), networkCodeClass = rock::opts$get("networkCodeClass"), idClass = rock::opts$get("idClass"), sectionClass = rock::opts$get("sectionClass"), uidClass = rock::opts$get("uidClass"), contextClass = rock::opts$get("contextClass"), rockLineClass = rock::opts$get("rockLineClass"), utteranceClass = rock::opts$get("utteranceClass"), codingClass = rock::opts$get("codingClass"), commentClass = rock::opts$get("commentClass"), yamlClass = rock::opts$get("yamlClass"))Arguments
x | A character vector with the source |
context | Optionally, lines to pass the contextClass |
codeClass,codeValueClass,idClass,sectionClass,uidClass,contextClass,utteranceClass,commentClass,networkCodeClass,rockLineClass,codingClass,yamlClass | The classes to use for, respectively, codes, code values,class instance identifiers (such as caseidentifiers or coder identifiers), section breaks, utteranceidentifiers, context, full utterances, comments, network codes, source lines, codings, and YAML chunks. All |
Value
The character vector with the replacements made.
Examples
### Add tags to a mini example sourceadd_html_tags("[[cid=participant1]]This is something this participant may have said.Just like this. [[thisIsACode]]---paragraph-break---And another utterance.");Apply multiple DiagrammeR global graph attributes
Description
Apply multiple DiagrammeR global graph attributes
Usage
apply_graph_theme(graph, ...)Arguments
graph | TheDiagrammeR::DiagrammeR graph to apply the attributes to. |
... | One or more character vectors of length three, where the first element isthe attribute, the second the value, and the third, the attribute type ( |
Value
TheDiagrammeR::DiagrammeR graph.
Examples
### Create an example sourceexampleSource <- '---codes: - id: parentCode label: Parent code children: - id: childCode1 - id: childCode2 - id: childCode3 label: Child Code parentId: parentCode children: [grandChild1, grandChild2]---';### Parse itparsedSource <- rock::parse_source( text = exampleSource );### Extract the deductive code tree from### the parsed sourcedeductiveCodeTree <- parsedSource$deductiveCodeTrees;### Convert it to a DiagrammeR graphminiGraph <- data.tree::ToDiagrammeRGraph( deductiveCodeTree );### Show the graphDiagrammeR::render_graph( miniGraph);### Apply a "theme" (three attributes)miniGraph_themed <- rock::apply_graph_theme( miniGraph, c("rankdir", "TB", "graph"), c("shape", "square", "node"), c("style", "solid", "node"), c("fontname", "Arial", "node"), c("fontcolor", "#0000BB", "node"), c("color", "#BB0000", "node") );### Show the updated graphDiagrammeR::render_graph( miniGraph_themed);Specify that something is a source
Description
This function converts an object to a character vector and marks it asa ROCK source.
Usage
as.rock_source(x)Arguments
x | The source contents. |
Value
A character vector with classrock_source.
Examples
exampleROCK <- rock::as.rock_source(c( "Some example text,", "and some more. [[look_a_code]]", "And the end."));### This can then be processed by other {rock}### functions, for example:rock::prettify_source( exampleROCK);Conversion between base10 and base30
Description
Note: this function is deprecated; use this function in the{squids}package!
Usage
base30toNumeric(x)numericToBase30(x)Arguments
x | The vector to convert (numeric for |
Details
The conversion functions from base10 to base30 and vice versa areused by thegenerate_uids() functions.
The symbols to represent the 'base 30' system are the 0-9followed by the alphabet without vowels but including the y (seesquids::squids-package).
Value
The converted vector (numeric forbase30toNumeric, character fornumericToBase30).
Examples
rock::numericToBase30( 654321);rock::base30toNumeric( rock::numericToBase30( 654321 ));Taking a vector, carry value over ('persistence')
Description
This function takes a value, and then replacesempty elements (NA or zero-length character values)with the last non-empty preceding element itencountered.
Usage
carry_over_values(x, noId = "no_id")Arguments
x | The vector |
noId | The value to add for the first empty elements |
Value
The vector with the carries over elements
Examples
rock::carry_over_values( c( NA, NA, 3, NA, NA, 7, NA, NA ));Concatenate to screen without spaces
Description
The cat0 function is to cat what paste0 is to paste; itsimply makes concatenating many strings without a separator easier.
Usage
cat0(..., sep = "")Arguments
... | The character vector(s) to print; passed tocat. |
sep | The separator to pass tocat, of course, |
Value
Nothing (invisibleNULL, likecat).
Examples
cat0("The first variable is '", names(mtcars)[1], "'.");Check for presence of a package
Description
This function efficiently checks for the presence of a packagewithout loading it (unlikelibrary() orrequire().This is useful to force yourself to use the package::functionsyntax for addressing functions; you can make sure required packagesare installed, but their namespace won't attach to the search path.
Usage
checkPkgs( ..., install = FALSE, load = FALSE, repos = "https://cran.rstudio.com")Arguments
... | A series of packages. If the packages are named, thenames are the package names, and the values are the minimum requiredpackage versions (see the second example). |
install | Whether to install missing packages from |
load | Whether to load packages (which is exactlynot the pointof this package, but hey, YMMV). |
repos | The repository to use if installing packages; defaultis the RStudio repository. |
Value
Invisibly, a vector of the available packages.
Examples
rock::checkPkgs('base');### Require a specific versionrock::checkPkgs(rock = "0.9.1");### This will show the error messagetryCatch( rock::checkPkgs( base = "99", stats = "42.5", rock = 2000 ), error = print);Get an item in a specific language
Description
This function takes a Narrative Response Model specification as used inNRM-based cognitive interviews, and composes an item based on thespecified template for that item, the specified stimuli, and therequested language.
Usage
ci_get_item(nrm_spec, item_id, language)Arguments
nrm_spec | The Narrative Response Model specification. |
item_id | The identifier of the requested item. |
language | The language of the stimuli. |
Value
A character value with the item.
Create a heatmap showing issues with items
Description
When conducting cognitive interviews, it can be useful to quickly inspectthe code distributions for each item. These heatmaps facilitate thatprocess.
Usage
ci_heatmap( x, nrmSpec = NULL, language = nrmSpec$defaultLanguage, wrapLabels = 80, itemOrder = NULL, itemLabels = NULL, itemIdentifier = "uiid", codingScheme = "peterson", itemlab = NULL, codelab = NULL, freqlab = "Count", plotTitle = "Cognitive Interview Heatmap", fillScale = ggplot2::scale_fill_viridis_c(), theme = ggplot2::theme_minimal())Arguments
x | The object with the parsed coded source(s) as resulting from acall to |
nrmSpec | Optionally, an imported Narrative Response Modelspecification, as imported with |
language | If |
wrapLabels | Whether to wrap the labels; if not |
itemOrder,itemLabels | Instead of specifying an NRM specification,you can also directly specify the item order and item labels. |
itemIdentifier | The column identifying the items; the class instanceidentifier prefix, e.g. if item identifiers are specified as |
codingScheme | The coding scheme, either as a string if it representsone of the cognitive interviewig coding schemes provided with the |
itemlab,codelab,freqlab | Labels to use for the item and code axesand for the frequency color legend ( |
plotTitle | The title to use for the plot |
fillScale | Convenient way to specify the fill scale (the colours) |
theme | Convenient way to specify the |
Value
The heatmap as a ggplot2 plot.
Examples
examplePath <- file.path(system.file(package="rock"), 'extdata');parsedCI <- rock::parse_source( file.path(examplePath, "ci_example_1.rock"));rock::ci_heatmap(parsedCI, codingScheme = "peterson");Import a Narrative Response Model specification
Description
Narrative Response Models are a description of the theory of how ameasurement instrument that measures a psychological construct works,geared towards conducting cognitive interviews to verify the validityof that measurement instrument. One a Narrative Response Model has beenimported, it can be used to generate interview schemes, overview of eachitem's narrative response model, and combined with coded cognitiveinterview notes or transcripts.
Usage
ci_import_nrm_spec( x, read_ss_args = list(exportGoogleSheet = TRUE), defaultLanguage = NULL, silent = rock::opts$get("silent"))## S3 method for class 'rock_ci_nrm'print(x, ...)Arguments
x | A path to a file or an URL to a Google Sheet, passedto |
read_ss_args | A named list with arguments to pass to |
defaultLanguage | Language to set as default language (by default,i.e. if |
silent | Whether to be silent or chatty. |
... | Additional arguments are ignored. |
Value
Arock_ci_nrm object.
Cleaning & editing sources
Description
These functions can be used to 'clean' one or more sources or perform search andreplace taks. Cleaning consists of two operations: splitting the source atutterance markers, and conducting search and replaces using regular expressions.
Usage
clean_source( input, output = NULL, replacementsPre = rock::opts$get("replacementsPre"), replacementsPost = rock::opts$get("replacementsPost"), extraReplacementsPre = NULL, extraReplacementsPost = NULL, removeNewlines = FALSE, removeTrailingNewlines = TRUE, rlWarn = rock::opts$get(rlWarn), utteranceSplits = rock::opts$get("utteranceSplits"), preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))clean_sources( input, output, outputPrefix = "", outputSuffix = "_cleaned", recursive = TRUE, filenameRegex = ".*", replacementsPre = rock::opts$get(replacementsPre), replacementsPost = rock::opts$get(replacementsPost), extraReplacementsPre = NULL, extraReplacementsPost = NULL, removeNewlines = FALSE, utteranceSplits = rock::opts$get(utteranceSplits), preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))search_and_replace_in_source( input, replacements = NULL, output = NULL, preventOverwriting = TRUE, encoding = "UTF-8", rlWarn = rock::opts$get(rlWarn), silent = FALSE)search_and_replace_in_sources( input, output, replacements = NULL, outputPrefix = "", outputSuffix = "_postReplacing", preventOverwriting = rock::opts$get("preventOverwriting"), recursive = TRUE, filenameRegex = ".*", encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | For |
output | For |
replacementsPre,replacementsPost | Each is a list of two-element vectors,where the first element in each vector contains a regular expression to search forin the source(s), and the second element contains the replacement (these are passedas |
extraReplacementsPre,extraReplacementsPost | To perform more replacementsthan the default set, these can be conveniently specified in |
removeNewlines | Whether to remove all newline characters from the source beforestarting to clean them.Be careful: if the source contains YAML fragments, thesewill also be affected by this, and will probably become invalid! |
removeTrailingNewlines | Whether to remove trailing newline characters(i.e. at the end of a character value in a character vector); |
rlWarn | Whether to let |
utteranceSplits | This is a vector of regular expressions that specify where toinsert breaks between utterances in the source(s). Such breakes are specified usingthe |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding of the source(s). |
silent | Whether to suppress the warning about not editing the cleaned source. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk. |
recursive | Whether to search all subdirectories ( |
filenameRegex | A regular expression to match against located files; onlyfiles matching this regular expression are processed. |
replacements | The strings to search & replace, as a list of two-element vectors,where the first element in each vector contains a regular expression to search forin the source(s), and the second element contains the replacement (these are passedas |
Details
The cleaning functions, when called with their default arguments, will do the following:
Double periods (
..) will be replaced with single periods (.)Four or more periods (
...or.....) will be replaced with three periodsThree or more newline characters will be replaced by one newline character (whichwill become more, if the sentence before that character marks the end of anutterance)
All sentences will become separate utterances (in a semi-smart manner;specifically, breaks in speaking, if represented by three periods, are notconsidered sentence ends, wheread ellipses ("…" or unicode 2026, see the example)are.
If there are comma's without a space following them, a space will be inserted.
Value
A character vector forclean_source, or a list of character vectors,forclean_sources.
Examples
exampleSource <-"Do you like icecream?Well, that depends\u2026 Sometimes, when it's..... Nice. Then I do,but otherwise... not really, actually."### Default settings:cat(clean_source(exampleSource));### First remove existing newlines:cat(clean_source(exampleSource, removeNewlines=TRUE));### Example with a YAML fragmentexampleWithYAML <-c( "Do you like icecream?", "", "", "Well, that depends\u2026 Sometimes, when it's..... Nice.", "Then I do,", "but otherwise... not really, actually.", "", "---", "This acts as some YAML. So this won't be split.", "Not real YAML, mind... It just has the delimiters, really.", "---", "This is an utterance again.");cat( rock::clean_source( exampleWithYAML ), sep="\n");exampleSource <-"Do you like icecream?Well, that depends\u2026 Sometimes, when it's..... Nice. Then I do,but otherwise... not really, actually."### Simple text replacements:cat(search_and_replace_in_source(exampleSource, replacements=list(c("\u2026", "..."), c("Nice", "Great"))));### Using a regular expression to capitalize all words following### a period:cat(search_and_replace_in_source(exampleSource, replacements=list(c("\\.(\\s*)([a-z])", ".\\1\\U\\2"))));Convert a character vector into an utterance vector
Description
Utterance vectors are split by the utterance marker. Note that ifx hasmore than one element, the separate elements will remain separate.
Usage
cleaned_source_to_utterance_vector( x, utteranceMarker = rock::opts$get("utteranceMarker"), fixed = FALSE, perl = TRUE)Arguments
x | The character vector. |
utteranceMarker | The utterance marker (by default, a newlinecharacter conform the ROCK standard). |
fixed | Whether the |
perl | If the |
Value
A character vector with separate utterances, splitbyutteranceMarker.
Examples
cleaned_source_to_utterance_vector("first\nsecond\nthird");Replace code identifiers with their full paths
Description
This function replaces the column names in themergedSourceDf data framein arock_parsedSource orrock_parsedSources object with the full pathsto those code identifiers.
Usage
codeIds_to_codePaths( x, stripRootsFromCodePaths = rock::opts$get("stripRootsFromCodePaths"))Arguments
x | A |
stripRootsFromCodePaths | Whether to strip the roots first (i.e. thetype of code) |
Value
An adaptedrock_parsedSource orrock_parsedSources object.
Get a vector to find the full paths based on the leaf code identifier
Description
This function names a vector with the leaf codeusing thecodeTreeMarker stored in theopts object as marker.
Usage
codePaths_to_namedVector(x)Arguments
x | A vector of code paths. |
Value
The named vector of code paths.
Examples
codePaths_to_namedVector( c("codes>reason>parent_feels", "codes>reason>child_feels"));Code frequencies separate by a variable
Description
Code frequencies separate by a variable
Usage
code_freq_by(x, by, codes = ".*", returnTidyDf = FALSE)Arguments
x | The object with parsed sources. |
by | The variables on which to split when computing code frequencies. |
codes | A regular expression specifying the codes fo which to computethe code frequencies. |
returnTidyDf | When |
Value
A data frame with the code frequencies
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);### Show code frequenciescode_freq_by(loadedExample, "nestingLevel");Create a frequency histogram for codes
Description
Create a frequency histogram for codes
Usage
code_freq_hist( x, codes = ".*", sortByFreq = "decreasing", forceRootStripping = FALSE, trimSourceIdentifiers = 20, ggplot2Theme = ggplot2::theme(legend.position = "bottom"), silent = rock::opts$get("silent"))Arguments
x | A parsed source(s) object. |
codes | A regular expression to select codes to include. |
sortByFreq | Whether to sort by frequency decreasingly( |
forceRootStripping | Force the stripping of roots, even if they aredifferent. |
trimSourceIdentifiers | If not |
ggplot2Theme | Can be used to specify theme elements for the plot. |
silent | Whether to be chatty or silent. |
Value
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);### Show code frequenciescode_freq_hist(loadedExample);Add one or more codes to one or more sources
Description
These functions add codes to one or moresources that were read with one of theloading_sources functions.
Usage
code_source( input, codes, indices = NULL, output = NULL, decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), rlWarn = rock::opts$get(rlWarn), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))code_sources( input, codes, output = NULL, indices = NULL, outputPrefix = "", outputSuffix = "_coded", decisionLabel = NULL, justification = NULL, justificationFile = NULL, recursive = TRUE, filenameRegex = ".*", preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | The source, or list of sources, asproduced by one of the |
codes | A named character vector, where each elementis the code to be added to the matching utterance, andthe corresponding name is either an utterance identifier(in which case the utterance with that identifier will becoded with that code), a code (in which case all utteranceswith that code will be coded with the new code as well), adigit (in which case the utterance at that line number inthe source will be coded with thatcode), or a regular expression, in which case all utterancesmatching that regular expression will be coded with thatsource. If specifying an utterance ID or code, make surethat the code delimiters are included (normally, two squarebrackets). |
indices | If |
output | If specified, the coded source will be written here. |
decisionLabel | A description of the (coding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing files. |
rlWarn | Whether to let |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
outputPrefix,outputSuffix | A prefix and/or suffix to prepend and/orappend to the filenames to distinguish them from the input filenames. |
recursive | Whether to also read files from all subdirectoriesof the |
filenameRegex | Only input files matching this patterns will be read. |
Value
Invisibly, the coded source object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceloadedExample <- rock::load_source(exampleFile);### Show line 71cat(loadedExample[71]);### Specify the rules to code all utterances### containing "Ipsum" with the code 'ipsum' and### all utterances containing the codecodeSpecs <- c("(?i)ipsum" = "ipsum", "BC|AD|\\d\\d\\d\\ds" = "timeRef");### Apply rulescodedExample <- code_source(loadedExample, codeSpecs);### Show line 71cat(codedExample[71]);### Also add code "foo" to utterances with code 'ipsum'moreCodedExample <- code_source(codedExample, c("[[ipsum]]" = "foo"));### Show line 71cat(moreCodedExample[71]);### Use the 'indices' argument to add the code 'bar' to### line 71overCodedExample <- code_source(moreCodedExample, "bar", indices=71);cat(overCodedExample[71]);Import a code book specification from a spreadsheet
Description
Import a code book specification from a spreadsheet
Usage
codebook_fromSpreadsheet( x, localBackup = NULL, exportGoogleSheet = TRUE, xlsxPkg = c("rw_xl", "openxlsx", "XLConnect"), silent = rock::opts$get("silent"))Arguments
x | The URL or path to a file. |
localBackup | If not |
exportGoogleSheet | If |
xlsxPkg | Which package to use to work with Excel spreadsheets. |
silent | Whether to be silent or chatty. |
Value
The code book specification as arock code book object
Examples
### Note that this will require an active### internet connection! This if statement### checks for that.if (tryCatch({readLines("https://google.com",n=1); TRUE}, error=function(x) FALSE)) { ### Read the example ROCK codebook gs_url <- paste0( "https://docs.google.com/spreadsheets/d/", "1gVx5uhYzqcTH6Jq7AYmsLvHSBaYaT-23c7ZhZF4jmps" ); ROCK_codebook <- rock::codebook_fromSpreadsheet(gs_url); ### Show a bit ROCK_codebook$metadata[1:3, ];}Convert a codebook specification to PDF
Description
Use this function to export your codebook specification to a PDFfile. To embed it in an R Markdown file, use!!! CREATE rock::knit_codebook() !!!
Usage
codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent"))Arguments
x | The codebook object (as produced by a call to |
file | The filename to save the codebook to. |
author | The author to specify in the PDF. |
headingLevel | The level of the top-most headings. |
silent | Whether to be silent or chatty. |
Value
x, invisibly
Examples
### Use a temporary file to write totmpFile <- tempfile(fileext = ".pdf");### Load an example (pre)registration specificationdata("exampleCodebook_1", package = "rock");rock::codebook_to_pdf( exampleCodebook_1, file = tmpFile);Convenience function to get a list of all available coding schemes
Description
Convenience function to get a list of all available coding schemes
Usage
codingSchemes_get_all()Value
A list of all available coding schemes
Examples
rock::codingSchemes_get_all();Collapse the occurrences in utterances into groups
Description
This function collapses all occurrences into groupssharing the same identifier, by default thestanzaIdidentifier ([[sid=..]]).
Usage
collapse_occurrences( parsedSource, collapseBy = "stanzaId", columns = NULL, logical = FALSE)Arguments
parsedSource | The parsed sources as provided by |
collapseBy | The column in the |
columns | The columns to collapse; if unspecified (i.e. |
logical | Whether to return the counts of the occurrences ( |
Value
A dataframe with one row for each value of ofcollapseBy and columnsforcollapseBy and each of thecolumns, with in the cells the counts (iflogical isFALSE) orTRUE orFALSE (iflogical isTRUE).
Examples
### Get path to example sourceexampleFile <- system.file("extdata", "example-1.rock", package="rock");### Parse example sourceparsedExample <- rock::parse_source(exampleFile);### Collapse logically, using a code (either occurring or not):collapsedExample <- rock::collapse_occurrences(parsedExample, collapseBy = 'childCode1');### Show result: only two rows left after collapsing,### because 'childCode1' is either 0 or 1:collapsedExample;### Collapse using weights (i.e. count codes in each segment):collapsedExample <- rock::collapse_occurrences(parsedExample, collapseBy = 'childCode1', logical=FALSE);Create an overview of coded fragments
Description
Collect all coded utterances and optionally add some context(utterances before and utterances after) to create an overviewof all coded fragments per code.
Usage
collect_coded_fragments( x, codes = ".*", context = 0, includeDescendents = FALSE, attributes = NULL, heading = NULL, headingLevel = 3, add_html_tags = TRUE, cleanUtterances = FALSE, omitEmptyCodes = TRUE, output = NULL, outputViewer = "viewer", template = "default", rawResult = FALSE, includeCSS = TRUE, preserveSpaces = TRUE, codeHeadingFormatting = rock::opts$get("codeHeadingFormatting"), codeHeadingFormatting_html = rock::opts$get("codeHeadingFormatting_html"), includeBootstrap = rock::opts$get("includeBootstrap"), preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
x | The parsed source(s) as provided by |
codes | The regular expression that matches the codes to include,or a character vector with codes or regular expressions for codes (whichwill be prepended with " |
context | How many utterances before and after the targetutterances to include in the fragments. If two values, the first is thenumber of utterances before, and the second, the number of utterancesafter the target utterances. |
includeDescendents | Whether to also collect the fragments coded withdescendent codes (i.e. child codes, 'grand child codes', etc; in otherwords, whether to collect the fragments recursively). |
attributes | To only select coded utterances matching one or morevalues for one or more attributes, pass a list where every element'sname is a valid (i.e. occurring) attribute name, and every element is acharacter value with a regular expression specifying all values for thatattribute to select. |
heading | Optionally, a title to include in the output. The titlewill be prefixed with |
headingLevel | The number of hashes to insert before the headings. |
add_html_tags | Whether to add HTML tags to the result. |
cleanUtterances | Whether to use the clean or the raw utteranceswhen constructing the fragments (the raw versions contain all codes). Note thatthis should be set to |
omitEmptyCodes | Whether to still show the title for codes that do notoccur or not. |
output | Here, a path and filename can be provided where theresult will be written. If provided, the result will be returnedinvisibly. |
outputViewer | If showing output, where to show the output: inthe console ( |
template | The template to load; either the name of oneof the ROCK templates (currently, only 'default' is available), orthe path and filename of a CSS file. |
rawResult | Whether to return the raw result, a list of thefragments, or one character value in markdown format. |
includeCSS | Whether to include the ROCK CSS in the returned HTML. |
preserveSpaces | Whether to preserve spaces in the output (replacingdouble spaces with " |
codeHeadingFormatting,codeHeadingFormatting_html | A character value of theform |
includeBootstrap | Whether to include the default bootstrap CSS. |
preventOverwriting | Whether to prevent overwriting of output files. |
silent | Whether to provide ( |
Details
By default, the output is optimized for inclusion in an R Markdowndocument. To optimize output for the R console or a plain textfile, without any HTML codes, setadd_html_tags to FALSE, andpotentially setcleanUtterances to only return the utterances,without the codes.
Value
Either a list of character vectors, or a single character value.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path( examplePath, "example-.rock" );### Parse single example sourceparsedExample <- rock::parse_source( exampleFile );### Show organised coded fragments in Markdowncat( rock::collect_coded_fragments( parsedExample ));### Only for the codes containing 'Code2', with### 2 lines of context (both ways)cat( rock::collect_coded_fragments( parsedExample, 'Code2', context = 2 ));### Parse multiple example sources### Load two example sourcesparsedExamples <- rock::parse_sources( examplePath, regex = "example-[1234].rock");cat( rock::collect_coded_fragments( parsedExamples, '[cC]ode2', context = 2 ));Vector compression helper functions
Description
These functions can help when compressing vectors. They always compresstheir input (x) into a single element by various means.
Usage
compress_with_sum(x)compress_with_or(x)Arguments
x | The vector to compress |
Details
compress_with_sum computes the sum of the elements, doing its best toconvert all input values to numeric values.compress_with_or returns0 if all elements areFALSE,0,NA orempty character values (""), and1 otherwise.
Value
The compressed element
Examples
rock::compress_with_sum(c(1, '1', 0));rock::compress_with_or(c(1, '1', 0));rock::compress_with_or(c(0, '', 0, FALSE));Confidence intervals for proportions, vectorized over all arguments
Description
This function simply computes confidence intervals for proportions.
Usage
confIntProp(x, n, conf.level = 0.95, plot = FALSE)Arguments
x | The number of 'successes', i.e. the number of events, observations,or cases that one is interested in. |
n | The total number of cases or observatons. |
conf.level | The confidence level. |
plot | Whether to plot the confidence interval in the binomial distribution. |
Details
This function is the adapted source code ofbinom.test(). Itusespbeta(), with some lines of code taken from thebinom.test() source. Specifically, the count for the lowcategory is specified as first 'shape argument' topbeta(), andthe total count (either the sum of the count for the low category and thecount for the high category, or the total number of cases ifcompareHiToLo isFALSE) minus the count for the low categoryas the second 'shape argument'.
Value
The confidence interval bounds in a twodimensional matrix, with thefirst column containing the lower bound and the second column containing theupper bound.
Author(s)
Unknown (seebinom.test(); adapted by Gjalt-Jorn Peters)
Maintainer: Gjalt-Jorn Petersrock@opens.science
See Also
Examples
### Simple case rock::confIntProp(84, 200); ### Using vectors rock::confIntProp(c(2,3), c(10, 20), conf.level=c(.90, .95, .99));Conveniently convert vectors to numeric
Description
Tries to 'smartly' convert factor and character vectors to numeric.
Usage
convertToNumeric(vector, byFactorLabel = FALSE)Arguments
vector | The vector to convert. |
byFactorLabel | When converting factors, whether to do thisby their label value ( |
Value
The converted vector.
Examples
rock::convertToNumeric(as.character(1:8));Convert 'rectangular' or spreadsheet-format data to one or more sources
Description
These functions first import data from a 'data format', such as spreadsheetsin.xlsx format, comma-separated values files (.csv), or SPSS datafiles (.sav). You can also just use R data frames (imported however youwant). These functions then use the columns you specified to convert thesedata to one (oneFile=TRUE) or more (oneFile=FALSE)rocksource file(s), optionally including class instanceidentifiers (such as case identifiers to identify participants, or locationidentifiers, or moment identifiers, etc) and using those to link theutterances to attributes from columns you specified. You can also precodethe utterances with codes you specify (if you ever would want to for somereason).
Usage
convert_df_to_source( data, output = NULL, omit_empty_rows = TRUE, cols_to_utterances = NULL, cols_to_ciids = NULL, cols_to_codes = NULL, cols_to_attributes = NULL, utterance_classId = NULL, utterance_comments = NULL, commentPrefix = ifelse(prependUIDs, repStr("#", 16), repStr("#", 3)), oneFile = TRUE, cols_to_sourceFilename = cols_to_ciids, cols_in_sourceFilename_sep = "_is_", sourceFilename_prefix = "source_", sourceFilename_suffix = "", ciid_labels = NULL, ciid_separator = "=", attributesFile = NULL, clean = TRUE, cleaningArgs = NULL, wordwrap = TRUE, wrappingArgs = NULL, prependUIDs = TRUE, UIDArgs = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))convert_csv_to_source( file, importArgs = NULL, omit_empty_rows = TRUE, output = NULL, cols_to_utterances = NULL, cols_to_ciids = NULL, cols_to_codes = NULL, cols_to_attributes = NULL, oneFile = TRUE, cols_to_sourceFilename = cols_to_ciids, cols_in_sourceFilename_sep = "=", sourceFilename_prefix = "source_", sourceFilename_suffix = "", ciid_labels = NULL, ciid_separator = "=", attributesFile = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))convert_csv2_to_source( file, importArgs = NULL, omit_empty_rows = TRUE, output = NULL, cols_to_utterances = NULL, cols_to_ciids = NULL, cols_to_codes = NULL, cols_to_attributes = NULL, oneFile = TRUE, cols_to_sourceFilename = cols_to_ciids, cols_in_sourceFilename_sep = "=", sourceFilename_prefix = "source_", sourceFilename_suffix = "", ciid_labels = NULL, ciid_separator = "=", attributesFile = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))convert_xlsx_to_source( file, importArgs = list(), omit_empty_rows = TRUE, output = NULL, cols_to_utterances = NULL, cols_to_ciids = NULL, cols_to_codes = NULL, cols_to_attributes = NULL, oneFile = TRUE, cols_to_sourceFilename = cols_to_ciids, cols_in_sourceFilename_sep = "=", sourceFilename_prefix = "source_", sourceFilename_suffix = "", ciid_labels = NULL, ciid_separator = "=", attributesFile = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))convert_sav_to_source( file, importArgs = NULL, omit_empty_rows = TRUE, output = NULL, cols_to_utterances = NULL, cols_to_ciids = NULL, cols_to_codes = NULL, cols_to_attributes = NULL, oneFile = TRUE, cols_to_sourceFilename = cols_to_ciids, cols_in_sourceFilename_sep = "=", sourceFilename_prefix = "source_", sourceFilename_suffix = "", ciid_labels = NULL, ciid_separator = "=", attributesFile = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))Arguments
data | The data frame containing the data to convert. |
output | If |
omit_empty_rows | Whether to omit rows where the values in the columnsspecified to convert to utterances are all empty (or contain onlywhitespace). |
cols_to_utterances | The names of the columns to convert to utterances,as a character vector. |
cols_to_ciids | The names of the columns to convert to class instanceidentifiers (e.g. case identifiers), as a named character vector, withthe values being the column names in the data frame, and the names being theclass instance identifiers (e.g. |
cols_to_codes | The names of the columns to convert to codes (i.e.codes appended to every utterance), as a character vector. When writing codes,it is not possible to also write multiple utterance columns(i.e. |
cols_to_attributes | The names of the columns to convert to attributes,as a named character vector, where each name is the name of the classinstance identifier to attach the attribute to. If only one column is passedin |
utterance_classId | When specifying multiple columns with utterances,and |
utterance_comments | A column with comments to be added to eachutterance. |
commentPrefix | If adding in comments, the prefix to use, typicallya number of hashes. Note that comment lines must start with a hash ( |
oneFile | Whether to store everything in one source, or create onesource for each row of the data (if this is set to |
cols_to_sourceFilename | The columns to use as unique part of thefilename of each source. These will be concatenated using |
cols_in_sourceFilename_sep | The separator to use when concatenatingthe |
sourceFilename_prefix,sourceFilename_suffix | Strings that areprepended and appended to the |
ciid_labels | The labels for the class instance identifiers. Classinstance identifiers have brief codes used in coding (e.g. 'cid' is thedefault for Case Identifiers, often used to identify participants) as wellas more 'readable' labels that are used in the attributes (e.g. 'caseId' isthe default class instance identifier for Case Identifiers). These can bespecified here as a named vector, with each element being the label andthe element's name the identifier. |
ciid_separator | The separator for the class instance identifier - bydefault, either an equals sign ( |
attributesFile | Optionally, a file to write the attributes to if youdon't want them to be written to the source file(s). |
clean,cleaningArgs | Whether to clean the utterances using |
wordwrap,wrappingArgs | Whether to word wrap the utterancesusing |
prependUIDs,UIDArgs | Whether to prepend utterance identifiers (UIDs)using |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding of the source(s). |
silent | Whether to suppress the warning about not editing the cleaned source. |
file | The path to a file containing the data to convert. |
importArgs | Optionally, a list with named elements representingarguments to pass when importing the file. |
Value
A source as a character vector.
Examples
### Get path to example filesexamplePath <- system.file("extdata", package="rock");### Get a path to file with example data frameexampleFile <- file.path(examplePath, "spreadsheet-import-test.csv");### Read data into a data framedat <- read.csv(exampleFile);### Convert data frame to a sourcesource_from_df <- convert_df_to_source( dat, cols_to_utterances = c("open_question_1", "open_question_2"), cols_to_ciids = c(cid = "id"), cols_to_attributes = c("age", "gender"), cols_to_codes = c("code_1", "code_2"), ciid_labels = c(cid = "caseId") );### Show the resultcat( source_from_df, sep = "\n");Count code occurrences
Description
Count code occurrences
Usage
count_occurrences(x, codes = ".*", matchRegexAgainstPaths = TRUE)Arguments
x | A parsed source(s) object. |
codes | A regular expression to select codes to include, or,alternatively, a character vector with literal code idenfitiers. |
matchRegexAgainstPaths | Whether to match the |
Value
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-3.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);### Show code occurrencesrock::count_occurrences( loadedExample);Create a coding scheme
Description
This function can be used to specify a coding scheme that can thenbe used in analysis.
Usage
create_codingScheme( id, label, codes, codingInstructions = NULL, description = "", source = "")codingScheme_petersoncodingScheme_levinecodingScheme_willisArguments
id | An identifier for this coding scheme, consisting only ofletters, numbers, and underscores (and not starting with a number). |
label | A short human-readable label for the coding scheme. |
codes | A character vector with the codes in this scheme. |
codingInstructions | Coding instructions; a named character vector,where each element is a code's coding instruction, and each element's nameis the corresponding code. |
description | A description of this coding scheme (i.e. for informationthat does not fit in the label). |
source | Optionally, a description, reference, or URL of a sourcefor this coding scheme. |
Format
An object of classrock_codingScheme of length 5.
An object of classrock_codingScheme of length 5.
An object of classrock_codingScheme of length 5.
Details
A number of coding schemes for cognitive interviews are provided:
- codingScheme_peterson
Coding scheme from Peterson, Peterson &Powell, 2017
- codingScheme_levine
Coding scheme from Levine, Fowler &Brown, 2005
- codingScheme_willis
Coding scheme from Willis, 1999
Value
The coding scheme object.
Create a co-occurrence matrix
Description
This function creates a co-occurrence matrix based on one or morecoded sources. Optionally, it plots a heatmap, simply by callingthestats::heatmap() function on that matrix.
Usage
create_cooccurrence_matrix( x, codes = x$convenience$codingLeaves, plotHeatmap = FALSE)Arguments
x | The parsed source(s) as provided by |
codes | The codes to include; by default, takes all codes. |
plotHeatmap | Whether to plot the heatmap. |
Value
The co-occurrence matrix; amatrix.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Parse a selection of example sources in that directoryparsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" );### Create cooccurrence matrixrock::create_cooccurrence_matrix(parsedExamples);Create HTML fragment with CSS styling
Description
Create HTML fragment with CSS styling
Usage
css( template = "default", includeBootstrap = rock::opts$get("includeBootstrap"))Arguments
template | The template to load; either the name of oneof the ROCK templates (currently, only 'default' is available), orthe path and filename of a CSS file. |
includeBootstrap | Whether to include the default bootstrap CSS. |
Value
A character vector with the HTML fragment.
Convert a document (.docx, .pdf, .odt, .rtf, or .html) to a plain text file
Description
This used to be a thin wrapper aroundtextreadr::read_document() that alsowrites the result tooutput, doing its best to correctly write UTF-8(based on the approach recommended inthis blog post). However,textreadr was archived from CRAN. It now directly wraps the functionsthattextreadr wraps:pdftools::pdf_text(),striprtf::read_rtf, andit usesxml2 to import.docx and.odt files, andrvest to import.html files, using the code from thetextreadr package.
Usage
doc_to_txt( input, output = NULL, encoding = rock::opts$get("encoding"), newExt = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
input | The path to the input file. |
output | The path and filename to write to. If this is a path toan existing directory (without a filename specified), the |
encoding | The encoding to use when writing the text file. |
newExt | The extension to append: only used if |
preventOverwriting | Whether to prevent overwriting existing files. |
silent | Whether to the silent or chatty. |
Value
The converted source, as a character vector.
Examples
### This example requires the {xml2} packageif (requireNamespace("xml2", quietly = TRUE)) { print( rock::doc_to_txt( input = system.file( "extdata/doc-to-test.docx", package="rock" ) ) );}An very rudimentary example codebook specification
Description
This is a simple and relatively short codebookspecification.
Usage
exampleCodebook_1Format
An example of a codebook specification
Expand categorical attribute variables to a series of dichotomous variables
Description
Expand categorical attribute variables to a series of dichotomous variables
Usage
expand_attributes( data, attributes, valueLabels = NULL, prefix = "", glue = "__", suffix = "", falseValue = 0, trueValue = 1, valueFirst = TRUE, append = TRUE)Arguments
data | The data frame, normally the |
attributes | The name of the attribute(s) to expand. |
valueLabels | It's possible to use different names for the createdvariables than the values of the attributes. This can be set with the |
prefix,suffix | The prefix and suffix to add to the variables namesthat are returned. |
glue | The glue to paste the first part ad the second part of thecomposite variable name together. |
falseValue,trueValue | The values to set for rows that, respectively,do not match and do match an attribute value. |
valueFirst | Whether to insert the attribute value first, or theattribute name, in the composite variable names. |
append | Whether to append the columns to the supplied dataframe or not. |
Value
A data.frame
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Create a categorical attribute columnparsedExample$qdt$age_group <- c(rep(c("<18", "18-30", "31-60", ">60"), each=19), rep(c("<18", ">60"), time = c(3, 4)));### Expand to four logical columnsparsedExample$qdt <- rock::expand_attributes( parsedExample$qdt, "age_group", valueLabels = c( "<18" = "youngest", "18-30" = "youngish", "31-60" = "oldish", ">60" = "oldest" ), valueFirst = FALSE);### Show some of the resulttable(parsedExample$qdt$age_group, parsedExample$qdt$age_group__youngest);table(parsedExample$qdt$age_group, parsedExample$qdt$age_group__oldish);Exporting tables to HTML
Description
This function exports data frames or matrices toHTML, sending output to one or more of the console,viewer, and one or more files.
Usage
exportToHTML( input, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS"))Arguments
input | Either a |
output | The output: a character vector with one or moreof " |
tableOutputCSS | The CSS to use for the HTML table. |
Value
Invisibly, the (potentially concatenated)input as charactervector.
Examples
exportToHTML(mtcars[1:5, 1:5]);Export a ROCK project to a single ROCKproject file
Description
Export a ROCK project to a single ROCKproject file
Usage
export_ROCKproject( output, path = ".", config = NULL, includeRegex = NULL, excludeRegex = NULL, createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get("silent"))Arguments
output | The file to write to; should have the extension |
path | The path with the ROCK project |
config | Optionally, a named list with configuration options tooverride. For supported options, see |
includeRegex | A regular expression used to select files to include inthe project file |
excludeRegex | A regular expression used to omit files from theproject file; selection takes place after the selection by |
createDirs | Whether to, if any directories in the |
preventOverwriting | If the output file already exists, whether toprevent it from being overwritten ( |
forceBaseZip | Whether to force using the |
silent | Whether to be chatty or silent |
Value
Invisibly,output.
Examples
### Get path to example projectexamplePath <- system.file( "ROCKprojects", "exportable-ROCKproject-1", package="rock" );### Get a temporary filename to write toprojectFilename <- tempfile( fileext = ".ROCKproject" );### Export itrock::export_ROCKproject( path = examplePath, output = projectFilename, silent = FALSE);Export codes to a plain text file
Description
These function can be used to convert one or more parsed sources to HTML,or to convert all sources to tabbed sections in Markdown.
Usage
export_codes_to_txt( input, output = NULL, codeTree = "fullyMergedCodeTrees", codingScheme = "codes", regex = ".*", onlyChildrenOf = NULL, leavesOnly = TRUE, includePath = TRUE, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))Arguments
input | An object of class |
output | THe filename to write to. |
codeTree | Codes from which code tree to export the codes. Valid optionsare |
codingScheme | With the ROCK, it's possible to use multiple coding scheme'sin parallel. The ROCK default is called |
regex | An optional regular expression: only codes matching this regularexpression will be selected. |
onlyChildrenOf | A character vector of one or more regular expressions thatspecify codes within which to search. For example, if the code tree contains codes |
leavesOnly | Whether to only write the leaves (i.e. codes that don't havechildren) or all codes in the code tree. |
includePath | Whether to only return the code itself (e.g. |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding to use when writing the exported source(s). |
silent | Whether to suppress messages. |
Value
A character vector.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Parse a selection of example sources in that directoryparsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" );### Show results of exporting the codesrock::export_codes_to_txt(parsedExamples);### Only show select a narrow set of codesrock::export_codes_to_txt( parsedExamples, leavesOnly=TRUE, includePath=FALSE, onlyChildrenOf = "inductFather", regex="3|5");Export the fully merged code tree(s)
Description
Export the fully merged code tree(s)
Usage
export_fullyMergedCodeTrees(x, file)Arguments
x | A parsed source(s) object. |
file | The file to save to. |
Value
Invisibly,NULL.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);tempFile <- tempfile(fileext = ".svg");### Export merged code treeexport_fullyMergedCodeTrees( loadedExample, tempFile);Export a merged source data frame
Description
Export a merged source data frame
Usage
export_mergedSourceDf_to_csv( x, file, exportArgs = list(fileEncoding = rock::opts$get("encoding")), preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))export_mergedSourceDf_to_csv2( x, file, exportArgs = list(fileEncoding = rock::opts$get("encoding")), preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))export_mergedSourceDf_to_xlsx( x, file, exportArgs = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))export_mergedSourceDf_to_sav( x, file, exportArgs = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
x | The object with parsed sources. |
file | The file to export to. |
exportArgs | Optionally, arguments to pass to the function to use toexport. |
preventOverwriting | Whether to prevent overwriting if the file alreadyexists. |
silent | Whether to be silent or chatty. |
Value
Silently, the object with parsed sources.
Export parsed sources to HTML or Markdown
Description
These function can be used to convert one or more parsed sources to HTML,or to convert all sources to tabbed sections in Markdown.
Usage
export_to_html( input, output = NULL, template = "default", fragment = FALSE, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))export_to_markdown( input, heading = "Sources", headingLevel = 2, template = "default", silent = rock::opts$get(silent))Arguments
input | An object of class |
output | For |
template | The template to load; either the name of oneof the ROCK templates (currently, only 'default' is available), orthe path and filename of a CSS file. |
fragment | Whether to include the CSS and HTML tags ( |
preventOverwriting | For |
encoding | For |
silent | Whether to suppress messages. |
heading,headingLevel | For |
Value
A character vector or a list of character vectors.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Parse a selection of example sources in that directoryparsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)");### Export results to a temporary directorytmpDir <- tempdir(check = TRUE);prettySources <- export_to_html(input = parsedExamples, output = tmpDir);### Show first oneprint(prettySources[[1]]);Extract the codings by each coder using the coderId
Description
Extract the codings by each coder using the coderId
Usage
extract_codings_by_coderId( input, recursive = TRUE, filenameRegex = ".*", postponeDeductiveTreeBuilding = TRUE, ignoreOddDelimiters = FALSE, encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))Arguments
input | The directory with the sources. |
recursive | Whether to also process subdirectories. |
filenameRegex | Only files matching this regular expression will be processed. |
postponeDeductiveTreeBuilding | Whether to build deductive code trees, or onlystore YAML fragments. |
ignoreOddDelimiters | Whether to throw an error when encountering an odd number ofYAML delimiters. |
encoding | The encoding of the files to read. |
silent | Whether to be chatty or silent. |
Value
An object with the read sources.
Extract the UIDs (or SQUIDs) from a vector
Description
Extract the UIDs (or SQUIDs) from a vector
Usage
extract_uids(x, returnSQUIDs = FALSE)Arguments
x | The vector |
returnSQUIDs | WHether to return the UIDs or the SQUIDs. |
Value
A vector with (SQ)UIDs
Examples
exampleText <- c( "Lorem ipsum dolor sit amet, consectetur", "adipiscing elit. Nunc non commodo ex,", "ac varius mi. Praesent feugiat nunc", "eget urna euismod lobortis. Sed", "hendrerit suscipit nisl, ac tempus", "magna porta et. Quisque libero massa,", "tempus vel tristique lacinia, tristique", "in nulla. Nam cursus enim dui, non", "ornare est tempor eu. Vivamus et massa", "consectetur, tristique magna eget,", "viverra elit.");withUIDs <- rock::prepend_ids_to_source( exampleText );rock::extract_uids( withUIDs);Convert a (pre)registration form to an R Markdown template
Description
This function creates an R Markdown template from a {preregr}(pre)registrations form specification. Pass it the URL to a GoogleSheet holding the (pre)registration form specification (in {preregr}format), see the"Creating a form from a spreadsheet"vignette), the path to a file with a spreadsheet holding such aspecification, or a loaded or imported {preregr} (pre)registration form.
Usage
form_to_rmd_template( x, file = NULL, title = NULL, author = NULL, date = "`r format(Sys.time(), \"%H:%M:%S on %Y-%m-%d %Z (UTC%z)\")`", output = "html_document", yaml = list(title = title, author = author, date = date, output = output), includeYAML = TRUE, chunkOpts = "echo=FALSE, results='hide'", justify = FALSE, headingLevel = 1, showSpecification = FALSE, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
x | The (pre)registration form (as produced by a callto |
file | Optionally, a file to save the html to. |
title | The title to specify in the template's YAML front matter. |
author | The author to specify in the template's YAML front matter. |
date | The date to specify in the template's YAML front matter. |
output | The output format to specify in the template's YAMLfront matter. |
yaml | It is also possible to specify the YAML front matter directlyusing this argument. If used, it overrides anything specified in |
includeYAML | Whether to include the YAML front matter or omit it. |
chunkOpts | The chunk options to set for the chunks in the template. |
justify | Whether to use |
headingLevel | The level of the top-most heading to use (thetitle of the (pre)registration form). |
showSpecification | Whether to show the specification in the Rmdoutput. When |
preventOverwriting | Set to |
silent | Whether to be silent or chatty. |
Value
x, invisibly
Examples
newForm <- preregr::form_create( title = "Example form", version = "0.1.0" );preregr::form_to_rmd_template( newForm);Generate a TSSID
Description
A TSSID is a Timestamped Source Identifier. It is a practicallyunique identifier for a source, conventionally the time and datethe source was produced (e.g. when the data were collected, for examplethe time and date of an interview) in the UTC timezone and in ISO 8601standard format.
Usage
generate_tssid(x = Sys.time(), addDelimiters = FALSE, designationSymbol = "=")Arguments
x | The date and time to use. |
addDelimiters | If |
designationSymbol | The symbol to use to designate an instanceidentifier for a class (can be " |
Value
The tssid
Examples
rock::generate_tssid();Generate utterance identifiers (UIDs)
Description
This function generates utterance identifiers. Utterance identifiers areShort Quasi-Unique Identifiers (SQUIDs) generated usingthesquids::squids() function.
Usage
generate_uids(x, origin = Sys.time(), follow = NULL, followBy = NULL)Arguments
x | The number of identifiers to generate. |
origin | The origin to use when generating the actualidentifiers; see the |
follow | A vector of one or more UIDs (or a list; lists arerecursively |
followBy | When following a vector of UIDs, this can be used tospecify the distance between the two vectors in centiseconds. |
Value
A vector of UIDs.
Examples
### Produce and store five UIDsfiveUIDs <- rock::generate_uids(5);### Look at themfiveUIDs;### Use a specific origin to be able to reproduce### a set of UIDs later (e.g. in a script)uidOrigin <- as.POSIXct("2025-05-21 21:53:25 CEST");rock::generate_uids( 5, origin = uidOrigin);### Produce five more UIDs to show### their 'progression'rock::generate_uids(5);### Produce a set of five UIDs that follow### the first set of five UIDsrock::generate_uids( 5, follow = fiveUIDs);### Follow with a 'distance' of 5 utterancesrock::generate_uids( 5, follow = fiveUIDs, followBy = 5);Generic underlying recoding function
Description
This function contains the general set of actions that are always usedwhen recoding a source (e.g. check the input, document thejustification, etc). Users should normally never call this function.
Usage
generic_recoding( input, codes, func, filenameRegex = ".*", filter = TRUE, output = NULL, outputPrefix = "", outputSuffix = "_recoded", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"), ...)Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | The codes to process |
func | The function to apply. |
filenameRegex | Only process files matching this regular expression. |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the coded source will be written here. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
... | Other arguments to pass to |
Value
Invisibly, the recoded source(s) or source(s) object.
Get the code identifiers a code's descendents
Description
Get the code identifiers of all children, or all descendents (i.e. includinggrand-children, grand-grand-children, etc) of a code with a given identifier.
Usage
get_childCodeIds( x, parentCodeId, returnNodes = FALSE, includeParentCode = FALSE)get_descendentCodeIds(x, parentCodeId, includeParentCode = FALSE)Arguments
x | The parsed sources object |
parentCodeId | The code identifier of the parent code |
returnNodes | For |
includeParentCode | Whether to include the parent codeidentifier in the result |
Value
A character vector with code identifiers (or a list of nodes)
Get the code identifiers from QNA codings
Description
Get the code identifiers from QNA codings
Usage
get_codeIds_from_qna_codings( x, within = "network", return = "all", includeUIDs = TRUE)Arguments
x | A parsed source or multiple parsed sources |
within | Which type of network coding to look in |
return | What to return ('all', 'nodes', 'edges', 'from', 'to') |
includeUIDs | Whether to return the UIDs as well |
Value
A character vector or data frame
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Read a souce coded with the Qualitative Network ApproachqnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) );rock::get_codeIds_from_qna_codings( qnaExample);Return all values from a nested list in a dataframe
Description
Return all values from a nested list in a dataframe
Usage
get_dataframe_from_nested_list(x, nestingIn = "children")Arguments
x | The nested list |
nestingIn | The name containing the nested lists |
Value
A dataframe
Examples
nestedList <- list( id = "x", value = "value for x", children = list( list( id = "y", value = "value for y" ), list( id = "z", value = "value for z" ) ) );str(nestedList);get_dataframe_from_nested_list(nestedList);Create a filter to select utterances in a source
Description
This function takes a character vector with regular expressions,a numeric vector with numeric indices, or a logical vector that is eitheras long as the source or has length 1; and then always returns a logicalvector of the same length as the source.
Usage
get_source_filter( source, filter, ignore.case = TRUE, invert = FALSE, perl = TRUE, ...)Arguments
source | The source to produce the filter for. |
filter | THe filtering criterion: a character vector with regular expressions,a numeric vector with numeric indices, or a logical vector that is eitheras long as the source or has length 1. |
ignore.case | Whether to apply the regular expression case sensitivelyor not (see |
invert | Whether to invert the result or not (i.e. whether the filterspecifies what you want to select ( |
perl | Whether the regular expression (if |
... | Any additional arguments are passed on to |
Value
A logical vector of the same length as the source.
Get the state transition data frame
Description
Get the state transition data frame
Usage
get_state_transition_df(x)Arguments
x | A state transition table as produced by a callto |
Value
A dataframe with columnsfromState,toState,andnrOfTransitions.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "state-example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Show the state transition probabilitiesexampleTable <- rock::get_state_transition_table( parsedExample);exampleStateDf <- rock::get_state_transition_df( exampleTable);Get the Dot code for a state transition graph
Description
Get the Dot code for a state transition graph
Usage
get_state_transition_dot( x, labelFun = base::round, labelFunArgs = list(digits = 2))Arguments
x | A state transition table as produced by a callto |
labelFun | A function to apply to the edge labels in preprocessing. |
labelFunArgs | Arguments to specify to |
Value
The Dot code for a state transition graph.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "state-example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Show the state transition probabilitiesexampleTable <- rock::get_state_transition_table( parsedExample);exampleStateDf <- rock::get_state_transition_df( exampleTable);exampleDotCode <- rock::get_state_transition_dot( exampleStateDf);DiagrammeR::grViz(exampleDotCode);Get the state transition table
Description
Get the state transition table
Usage
get_state_transition_table(x, rawClassIdentifierCol = "state_raw")Arguments
x | A parsed source document as provided by |
rawClassIdentifierCol | The identifier of the column in |
Value
A table, with the 'from' states as rows and the 'to' states as columns
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "state-example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Show the state transition probabilitiesrock::get_state_transition_table( parsedExample);Get utterances and codes from source
Description
This is a convenience function to use when displaying a source. It returnsan object with the raw and clean utterances in a source, as well as theutterance identifiers and a list with vectors of the codes for eachutterance.
Usage
get_utterances_and_codes_from_source(x, ...)Arguments
x | Either the result of a call to |
... | Arguments to |
Value
A list containing$utterances_raw,$utterances_clean,$uids$,$codeMatches, and$codesPerUtterance.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceres <- rock::get_utterances_and_codes_from_source( exampleFile );Return one or more values from a nested list in a list of vectors
Description
Return one or more values from a nested list in a list of vectors
Usage
get_vectors_from_nested_list(x, valuesIn = NULL, nestingIn = "children")Arguments
x | The nested list |
valuesIn | The names holding the values to return (in vectors) |
nestingIn | The name containing the nested lists |
Value
A list of vectors.
Examples
nestedList <- list( id = "x", value = "value for x", children = list( list( id = "y", value = "value for y" ), list( id = "z", value = "value for z" ) ) );str(nestedList);get_vectors_from_nested_list( nestedList, c("id", "value"));Print a heading
Description
This is just a convenience function to print a markdown or HTML heading ata given 'depth'.
Usage
heading( ..., headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = TRUE)Arguments
... | The heading text: pasted together with no separator. |
headingLevel | The level of the heading; the default can be setwith e.g. |
output | Whether to output to HTML (" |
cat | Whether to cat (print) the heading or just invisibly return it. |
Value
The heading, invisibly.
Examples
heading("Hello ", "World", headingLevel=5);### This produces: "\n\n##### Hello World\n\n"Make a vector of strings into headings
Description
This is just a convenience function to convert a vector of strings intomarkdown or HTML headings at a given 'depth'.
Usage
heading_vector( x, headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = FALSE)Arguments
x | The vector. |
headingLevel | The level of the heading; the default can be setwith e.g. |
output | Whether to output to HTML (" |
cat | Whether to cat (print) the heading or just invisibly return it. |
Value
The heading, invisibly.
Examples
rock::heading_vector(c("Hello ", "World"), headingLevel=5);### This produces: "\n\n##### Hello\n\n" and### "\n\n##### World\n\n"Generic convenience function to create a heatmap
Description
Generic convenience function to create a heatmap
Usage
heatmap_basic( data, x, y, fill, xLab = x, yLab = y, fillLab = fill, plotTitle = "Heatmap", fillScale = ggplot2::scale_fill_viridis_c(), theme = ggplot2::theme_minimal())Arguments
data | A data frame |
x,y,fill | The variables (columns) in |
xLab,yLab,fillLab | The labels to use for the x axis, y axis, and fill,respectively |
plotTitle | The plot title. |
fillScale | The fill scale. |
theme | The theme. |
Value
The heatmap, as a ggplot2 object.
Examples
rock::heatmap_basic(mtcars, 'am', 'cyl', 'mpg');Import a ROCK project from a ROCKproject file
Description
Import a ROCK project from a ROCKproject file
Usage
import_ROCKproject( input, path = ".", createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get(silent))Arguments
input | The path to the ROCK project file (typically with the extension |
path | The path where to store the ROCK project |
createDirs | Whether to, if the |
preventOverwriting | If the path already contains files, whether toprevent them from being overwritten ( |
forceBaseZip | Whether to force using the |
silent | Whether to be chatty or silent |
Value
Invisibly,output.
Examples
### Get path to example projectexampleProjectFile <- system.file( "ROCKprojects", "example1.ROCKproject", package="rock" );### Get a temporary directory to write totemporaryDir <- tempdir();### Import the projectrock::import_ROCKproject( input = exampleProjectFile, path = temporaryDir, silent = FALSE);Import a source from Google Documents
Description
Import a source from Google Documents
Usage
import_source_from_gDocs(x, localFile = NULL)Arguments
x | The URL to the source: has to be viewable publicly! |
localFile | A local file (where to store a local backup). |
Value
The source contents.
Examples
### Note that this will require an active### internet connection! This if statement### checks for that.if (tryCatch({readLines("https://google.com",n=1); TRUE}, error=function(x) FALSE)) { gDocs_url <- paste0( "https://docs.google.com/document/d/", "1iACYjV7DdCjOmfgX6KEMtCcCjuuXD3iuikTSGWtsK84", "/edit?usp=sharing" ); ### Import the source exampleSource <- import_source_from_gDocs( gDocs_url ); ### Show the downloaded file: exampleSource; ### Parse the source: parsedExampleSource <- rock::parse_source( exampleSource ); ### Imported; the comments are gone: parsedExampleSource$qdt$utterances_raw;}Read sources from a directory, parse them, and show coded fragments and code tree
Description
This function combines successive calls toparse_sources(),collect_coded_fragments() andshow_inductive_code_tree().
Usage
inspect_coded_sources( path, parse_args = list(extension = "rock|dct", regex = NULL, recursive = TRUE, ignoreOddDelimiters = FALSE, encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent")), fragments_args = list(codes = ".*", context = 0), inductive_tree_args = list(codes = ".*", output = "both", headingLevel = 3), deductive_tree_args = list())Arguments
path | The path containing the sources to parse and inspect. |
parse_args | The arguments to pass to |
fragments_args | The arguments to pass to |
inductive_tree_args | The arguments to passto |
deductive_tree_args | Not yet implemented. |
Value
The parsedSources object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Inspect a selection of example sources - this takes too long### to test, so hence the 'donttest' directive.rock::inspect_coded_sources( examplePath, parse_args = list(regex = "test(.txt|.rock)"));Load a source from a file or a string
Description
These functions load one or more source(s) from a file ora string and store it in memory for further processing.Note that you'll probably want to clean the sourcesfirst, using one of theclean_sources() functions,and you'll probably want to add utterance identifiersto each utterance using one of theprepending_uids()functions.
Usage
load_source( input, encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"), rlWarn = rock::opts$get(rlWarn), diligentWarnings = rock::opts$get("diligentWarnings"))load_sources( input, filenameRegex = ".*", ignoreRegex = NULL, recursive = TRUE, full.names = FALSE, encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | The filename or contents of the sourcefor |
encoding | The encoding of the file(s). |
silent | Whether to be chatty or quiet. |
rlWarn | Whether to let |
diligentWarnings | Whether to display very diligent warnings. |
filenameRegex | A regular expression to match against located files; onlyfiles matching this regular expression are processed. |
ignoreRegex | Regular expression indicating which files to ignore. Thisis a perl-style regular expression (seebase::regex). |
recursive | Whether to search all subdirectories ( |
full.names | Whether to store source names as filenames only or whetherto include paths. |
Value
Invisibly, an R character vector ofclassesrock_source andcharacter.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceloadedSource <- rock::load_source(exampleFile);Make a ROCK project configuration file
Description
This function creates a ROCK project configuration file in the YAMLformat. See the Details section for more information.
Usage
make_ROCKproject_config( project = list(title = "Default title", authors = "Authors", authorIds = NULL, version = "1.0", ROCK_version = "1.0", ROCK_project_version = "1.0", date_created = format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z"), date_modified = format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z")), codebook = list(urcid = "", embedded = NULL, local = ""), sources = list(extension = ".rock", regex = NULL, dirsToIncludeRegex = "data/", recursive = TRUE, dirsToExcludeRegex = NULL, filesToIncludeRegex = NULL, filesToExcludeRegex = NULL), workflow = list(pipeline = NULL, actions = NULL), extra = NULL, path = NULL)Arguments
project | A named list with the project metadata. |
codebook | A named list with the project's codebook. |
sources | A named list with the project's source import settings. |
workflow | A named list with the project's workflow settings. |
extra | A named list with any additional things you want to store in theproject's configuration file. One never knows whether being able to do thatcomes in handy at some point. |
path | If not |
Details
For more information about the ROCK project configuration file format,see theROCKproject-format vignette. You can view this from R using:
vignette("ROCKproject-format", package="rock");
You can also visit it athttps://rock.opens.science/articles/ROCKproject-format.html.
Value
A list with the passed configuration in a list called$input, and as YAML in a character vector called$yaml.
Examples
### To get the default configuration,### just pass no arguments:defaultConfig <- rock::make_ROCKproject_config();### You can then extract the object with settingsconfig <- defaultConfig$input;### Edit some of themconfig$project$title <- "Some new title";### Call the function again with the new argumentsmyConfig <- rock::make_ROCKproject_config( project = config$project, codebook = config$codebook, sources = config$sources, workflow = config$workflow, extra = config$extra );### View the resultcat(myConfig$yaml);Masking sources
Description
These functions can be used to mask a set of utterances or one or more sources.
Usage
mask_source( input, output = NULL, proportionToMask = 1, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), rlWarn = rock::opts$get(rlWarn), maskRegex = "[[:alnum:]]", maskChar = "X", perl = TRUE, silent = rock::opts$get(silent))mask_sources( input, output, proportionToMask = 1, outputPrefix = "", outputSuffix = "_masked", maskRegex = "[[:alnum:]]", maskChar = "X", perl = TRUE, recursive = TRUE, filenameRegex = ".*", filenameReplacement = c("_PRIVATE_", "_public_"), preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))mask_utterances( input, proportionToMask = 1, maskRegex = "[[:alnum:]]", maskChar = "X", perl = TRUE)Arguments
input | For |
output | For |
proportionToMask | The proportion of utterances to mask, from 0 (none) to1 (all). |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding of the source(s). |
rlWarn | Whether to let |
maskRegex | A regular expresssion (regex) specifying the characters tomask (i.e. replace with the masking character). |
maskChar | The character to replace the character to mask with. |
perl | Whether the regular expression is a perl regex or not. |
silent | Whether to suppress the warning about not editing the cleaned source. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk. |
recursive | Whether to search all subdirectories ( |
filenameRegex | A regular expression to match against located files; onlyfiles matching this regular expression are processed. |
filenameReplacement | A character vector with two elements that represent,respectively, the |
Value
A character vector formask_utterance andmask_source, or a list ofcharacter vectors, formask_sources.
Examples
### Mask text but not the codesrock::mask_utterances( paste0( "Lorem ipsum dolor sit amet, consectetur adipiscing ", "elit. [[expAttitude_expectation_73dnt5z1>earplugsFeelUnpleasant]]" ))Match the corresponding indices of (YAML) delimiters in a sequential list
Description
This is just a convenience function that takes a vector of deliminatersand returns a list of delimiter pairs.
Usage
match_consecutive_delimiters( x, errorOnInvalidX = FALSE, errorOnOdd = FALSE, onOddIgnoreFirst = FALSE)Arguments
x | The vector with delimiter indices |
errorOnInvalidX | Whether to return |
errorOnOdd | Whether to throw an error if the number of delimiterindices is odd. |
onOddIgnoreFirst | If the number of delimiter indices is odd and noerror is thrown, whether to ignore the first ( |
Value
A list where each element is a two-element vector with the twoconsecutive delimiters
Examples
rock::match_consecutive_delimiters( c(1, 3, 5, 10, 19, 25, 30, 70));exampleText <- c( "some text", "delimiter", "more text", "delimiter", "filler text", "intentionally left blank", "delimiter", "final text", "delimiter");rock::match_consecutive_delimiters( grep( "delimiter", exampleText ));Merge source files by different coders
Description
This function takes sets of sources and merges them using the utteranceidentifiers (UIDs) to match them.
Usage
merge_sources( input, output, outputPrefix = "", outputSuffix = "_merged", primarySourcesRegex = ".*", primarySourcesIgnoreRegex = outputSuffix, primarySourcesPath = input, recursive = TRUE, primarySourcesRecursive = recursive, filenameRegex = ".*", primarySourcesFileList = NULL, sourcesFileList = NULL, postponeDeductiveTreeBuilding = TRUE, ignoreOddDelimiters = FALSE, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent), inheritSilence = FALSE)Arguments
input | The directory containing the input sources. |
output | The path to the directory where to store the merged sources.This path will be created with a warning if it does not exist. An exceptionis if " |
outputPrefix,outputSuffix | A pre- and/or suffix to add to the filenamewhen writing the merged sources (especially useful when writing them to thesame directory). |
primarySourcesRegex | A regular expression that specifies how torecognize the primary sources (i.e. the files used as the basis, to whichthe codes from other sources are added). |
primarySourcesIgnoreRegex | A regular expression that specifies whichfiles to ignore as primary files. |
primarySourcesPath | The path containing the primary sources. |
recursive,primarySourcesRecursive | Whether to read files fromsub-directories ( |
filenameRegex | Only files matching this regular expression are read. |
primarySourcesFileList,sourcesFileList | Alternatively to using regularexpressions, lists of full paths and filenames to the primary sources and allsources to process can be specified using these arguments. If this is used,neither can be |
postponeDeductiveTreeBuilding | Whether to imediately try to build the deductivetree(s) based on the information in this file ( |
ignoreOddDelimiters | If an odd number of YAML delimiters is encountered, whether thisshould result in an error ( |
preventOverwriting | Whether to prevent overwriting existing files or not. |
encoding | The encoding of the file to read (in |
silent | Whether to provide ( |
inheritSilence | If not silent, whether to let functions calledby |
Value
Invisibly, a list of the parsed, primary, and merged sources.
Convert a number to a date using Excel's system
Description
Convert a number to a date using Excel's system
Usage
number_as_xl_date(x)Arguments
x | The number(s) |
Value
The date(s)
Examples
preregr::number_as_xl_date(44113);Options for the rock package
Description
Therock::opts object contains three functions to set, get, and resetoptions used by the rock package. Userock::opts$set to set options,rock::opts$get to get options, orrock::opts$reset to reset specific orall options to their default values.
Usage
optsFormat
An object of classlist of length 4.
Details
It is normally not necessary to get or setrock options. The defaults implementthe Reproducible Open Coding Kit (ROCK) standard, and deviating from these defaultstherefore means the processed sources and codes are not compatible and cannot beprocessed by other software that implements the ROCK. Still, in some cases thisdegree of customization might be desirable.
The following arguments can be passed:
- ...
For
rock::opts$set, the dots can be used to specify the optionsto set, in the formatoption = value, for example,utteranceMarker = "\n". Forrock::opts$reset, a list of options to be reset can be passed.- option
For
rock::opts$set, the name of the option to set.- default
For
rock::opts$get, the default value to return if theoption has not been manually specified.
Some of the options that can be set (seerock::opts$defaults for thefull list):
- codeRegexes
A named character vector with one or more regularexpressions that specify how to extract the codes (that were used to code thesources). These regular expressionsmust each contain one capturing groupto capture the codes.
- idRegexes
A named character vector with one or more regularexpressions that specify how to extract the different types ofidentifiers. These regular expressionsmust each contain one capturing groupto capture the identifiers.
- sectionRegexes
A named character vector with one or more regularexpressions that specify how to extract the different types of sections.
- autoGenerateIds
The names of the
idRegexesthat, if missing, should receiveautogenerated identifiers (which consist of 'autogenerated_' followed by anincrementing number).- noCodes
This regular expression is matched with all codes after they have beenextracted using the
codeRegexesregular expression (i.e. they're matched against thecodes themselves without, for example, the square brackets in the default code regex). Anycodes matching thisnoCodesregular expression will beignored, i.e., removed from thelist of codes.- inductiveCodingHierarchyMarker
For inductive coding, this marker is used to indicatehierarchical relationships between codes. The code at the left hand side of this marker willbe considered the parent code of the code on the right hand side. More than two levelscan be specified in one code (for example, if the
inductiveCodingHierarchyMarkeris '>',the codegrandparent>child>grandchildwould indicate codes at three levels.- attributeContainers
The name of YAML fragments containing case attributes (e.g.metadata, demographic variables, quantitative data about cases, etc).
- codesContainers
The name of YAML fragments containing (parts of) deductive codingtrees.
- delimiterRegEx
The regular expression that is used to extract the YAML fragments.
- codeDelimiters
A character vector of two elementsspecifying the opening and closing delimiters of codes (conformthe default ROCK convention, two square brackets). The squarebrackets will be escaped; other characters will not, but willbe used as-is.
- ignoreRegex
The regular expression that is used to delete lines before any otherprocessing. This can be used to enable adding comments to sources, which are then ignoredduring analysis.
- includeBootstrap
Whether to include the default bootstrap CSS.
- utteranceMarker
How to specify breaks between utterances in the source(s). TheROCK convention is to use a newline (
\\n).- coderId
A regular expression specifying the coder identifier, specifiedsimilarly to the codeRegexes.
- idForOmittedCoderIds
The identifier to use for utterances that do nothave a coder id (i.e. utterance that occur in a source that does not specifya coder id, or above the line where a coder id is specified).
Examples
### Get the default utteranceMarkerrock::opts$get(utteranceMarker);### Set it to a custom version, so that every line starts with a piperock::opts$set(utteranceMarker = "\n|");### Check that it workedrock::opts$get(utteranceMarker);### Reset this option to its default valuerock::opts$reset(utteranceMarker);### Check that the reset worked, toorock::opts$get(utteranceMarker);Padd a character vector
Description
Padd a character vector
Usage
padString(x, width, padding = " ")Arguments
x | The character vector |
width | The width to pad to |
padding | The character to pad with |
Value
x with padding appended to each element
Examples
padString( c("One", "Two", "Three" ), width = 7);Parsing sources
Description
These function parse one (parse_source) or more (parse_sources) sources and thecontained identifiers, sections, and codes.
Usage
parse_source( text, file, utteranceLabelRegexes = NULL, ignoreOddDelimiters = FALSE, checkClassInstanceIds = rock::opts$get(checkClassInstanceIds), postponeDeductiveTreeBuilding = FALSE, filesWithYAML = NULL, mergeAttributes = TRUE, removeSectionBreakRows = rock::opts$get("removeSectionBreakRows"), removeIdentifierRows = rock::opts$get("removeIdentifierRows"), removeEmptyRows = rock::opts$get("removeEmptyRows"), suppressDuplicateInstanceWarnings = rock::opts$get("suppressDuplicateInstanceWarnings"), rlWarn = rock::opts$get("rlWarn"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))## S3 method for class 'rock_parsedSource'print(x, prefix = "### ", ...)parse_sources( path, extension = "rock|dct", regex = NULL, recursive = TRUE, removeSectionBreakRows = rock::opts$get("removeSectionBreakRows"), removeIdentifierRows = rock::opts$get("removeIdentifierRows"), removeEmptyRows = rock::opts$get("removeEmptyRows"), suppressDuplicateInstanceWarnings = rock::opts$get("suppressDuplicateInstanceWarnings"), filesWithYAML = NULL, ignoreOddDelimiters = FALSE, checkClassInstanceIds = rock::opts$get("checkClassInstanceIds"), mergeInductiveTrees = FALSE, encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))## S3 method for class 'rock_parsedSources'print(x, prefix = "### ", ...)## S3 method for class 'rock_parsedSources'plot(x, ...)Arguments
text,file | As |
utteranceLabelRegexes | Optionally, a list with two-element vectorsto preprocess utterances before they are stored as labels (these 'utteranceperl regular expression! |
ignoreOddDelimiters | If an odd number of YAML delimiters is encountered, whether thisshould result in an error ( |
checkClassInstanceIds | Whether to check for the occurrence of classinstance identifiers specified in the attributes. |
postponeDeductiveTreeBuilding | Whether to imediately try to build the deductivetree(s) based on the information in this file ( |
filesWithYAML | Any additional files to process to look for YAML fragments. |
mergeAttributes | Whether to merge the data frame with the attributesinto the qualitative data table (i.e., the data frame with the datafragments and codes). |
removeSectionBreakRows,removeIdentifierRows,removeEmptyRows | Whether toremove from the QDT, respectively: rows containing section breaks; rowscontaining only (class instance) identifiers; and empty rows. |
suppressDuplicateInstanceWarnings | Whether to suppress warnings aboutduplicate instances (as resulting from inconsistent specifications ofattributes for class instances). |
rlWarn | Whether to let |
encoding | The encoding of the file to read (in |
silent | Whether to provide ( |
x | The object to print. |
prefix | The prefix to use before the 'headings' of the printed result. |
... | Any additional arguments are passed on to the default print method. |
path | The path containing the files to read. |
extension | The extension of the files to read; files with other extensions willbe ignored. Multiple extensions can be separated by a pipe ( |
regex | Instead of specifing an extension, it's also possible to specify a regularexpression; only files matching this regular expression are read. If specified, |
recursive | Whether to also process subdirectories ( |
mergeInductiveTrees | Merge multiple inductive code trees into one; thisfunctionality is currently not yet implemented. |
Value
Forrock::parse_source(), an object of classrock_parsedSource;forrock::parse_sources(), an object of classrock_parsedSources. Theseobjects contain the original source(s) as well as the final data frame withutterances and codes, as well as the code structures.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Show inductive code tree for the codes### extracted with the regular expression specified with### the name 'codes':parsedExample$inductiveCodeTrees$codes;### If you want `rock` to be chatty, use:parsedExample <- rock::parse_source(exampleFile, silent=FALSE);### Parse as selection of example sources in that directoryparsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" );### Show combined inductive code tree for the codes### extracted with the regular expression specified with### the name 'codes':parsedExamples$inductiveCodeTrees$codes;### Show a souce coded with the Qualitative Network ApproachqnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) );Parsing sources separately for each coder
Description
Parsing sources separately for each coder
Usage
parse_source_by_coderId( input, ignoreOddDelimiters = FALSE, postponeDeductiveTreeBuilding = TRUE, rlWarn = rock::opts$get(rlWarn), encoding = "UTF-8", silent = TRUE)parse_sources_by_coderId( input, recursive = TRUE, filenameRegex = ".*", ignoreOddDelimiters = FALSE, postponeDeductiveTreeBuilding = TRUE, encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))Arguments
input | For |
ignoreOddDelimiters | If an odd number of YAML delimiters is encountered, whether thisshould result in an error ( |
postponeDeductiveTreeBuilding | Whether to imediately try to build the deductivetree(s) based on the information in this file ( |
rlWarn | Whether to let |
encoding | The encoding of the file to read (in |
silent | Whether to provide ( |
recursive | Whether to search all subdirectories ( |
filenameRegex | A regular expression to match against located files; onlyfiles matching this regular expression are processed. |
Value
Forrock::parse_source_by_coderId(), an object ofclassrock_parsedSource; forrock::parse_sources_by_coderId(), anobject of classrock_parsedSources. These objects contain the originalsource(s) as well as the final data frame with utterances and codes, aswell as the code structures.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source_by_coderId(exampleFile);Create an ENA network out of one or more parsed sources
Description
Create an ENA network out of one or more parsed sources
Usage
parsed_sources_to_ena_network( x, unitCols, conversationCols = "originalSource", codes = x$convenience$codingLeaves, metadata = x$convenience$attributesVars)Arguments
x | The parsed source(s) as provided by |
unitCols | The columns that together define units (e.g. utterances in eachsource that belong together, for example because they're about the same topic). |
conversationCols | The columns that together define conversations (e.g. separatesources, but can be something else, as well). |
codes | The codes to include; by default, takes all codes. |
metadata | The columns in the merged source dataframe that contain themetadata. By default, takes all read metadata. |
Value
The result of a call torENA::ena.plot.network(), if that isinstalled.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Parse a selection of example sources in that directoryparsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" );### Add something to indicate which units belong together; normally,### these would probably be indicated using one of the identifier,### for example the stanza identifiers, the sid'snChunks <- nrow(parsedExamples$mergedSourceDf) %/% 10;parsedExamples$mergedSourceDf$units <- c(rep(1:nChunks, each=10), rep(max(nChunks), nrow(parsedExamples$mergedSourceDf) - (10*nChunks)));### Generate ENA plotenaPlot <- rock::parsed_sources_to_ena_network(parsedExamples, unitCols='units');### Show the resulting plotprint(enaPlot);Prepend lines with one or more class instance identifiers to one or more sources
Description
These functions add lines with class instance identifiers to the beginningof one or more sources that were read with one of theloading_sources functions.
Usage
prepend_ciids_to_source( input, ciids, output = NULL, allOnOneLine = FALSE, designationSymbol = "=", preventOverwriting = rock::opts$get("preventOverwriting"), rlWarn = rock::opts$get(rlWarn), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))prepend_ciids_to_sources( input, ciids, output = NULL, outputPrefix = "", outputSuffix = "_coded", recursive = TRUE, filenameRegex = ".*", preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | The source, or list of sources, asproduced by one of the |
ciids | A named character vector, where each element's nameis the class identifier (e.g. "codeId" or "participantId") and eachelement is the class instance identifier. |
output | If specified, the coded source will be written here. |
allOnOneLine | Whether to add all class instance identifiers to oneline ( |
designationSymbol | The symbol to use to designate an instanceidentifier for a class (can be " |
preventOverwriting | Whether to prevent overwriting existing files. |
rlWarn | Whether to let |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
outputPrefix,outputSuffix | A prefix and/or suffix to prepend and/orappend to the filenames to distinguish them from the input filenames. |
recursive | Whether to also read files from all subdirectoriesof the |
filenameRegex | Only input files matching this patterns will be read. |
Value
Invisibly, the coded source object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceloadedExample <- rock::load_source(exampleFile);### Add a coder identifierloadedExample <- rock::prepend_ciids_to_source( loadedExample, c("codeId" = "iz0dn96") );### Show lines 1-5cat(loadedExample[1:5]);Prepending unique utterance identifiers
Description
This function prepends unique utterance identifiers to eachutterance (line) in a source. Note that you'll probably wantto clean the sources usingclean_sources() first.
Usage
prepend_ids_to_source( input, output = NULL, origin = Sys.time(), follow = NULL, followBy = NULL, rlWarn = rock::opts$get(rlWarn), preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))prepend_ids_to_sources( input, output = NULL, outputPrefix = "", outputSuffix = "_withUIDs", origin = Sys.time(), follow = NULL, followBy = NULL, uidSpacing = NULL, preventOverwriting = rock::opts$get(preventOverwriting), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent))Arguments
input | The filename or contents of the sourcefor |
output | The filename where to write the resulting file for |
origin | The time to use for the first identifier. |
follow | A vector of one or more UIDs (or a list; lists arerecursively |
followBy | When following a vector of UIDs, this can be used tospecify the distance between the two vectors (see |
rlWarn | Whether to let |
preventOverwriting | Whether to overwrite existing files ( |
encoding | The encoding of the file(s). |
silent | Whether to be chatty or quiet. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk. |
uidSpacing | The number of UID spaces to leave between sources (in casemore data may follow in with source). |
Value
The source with prepended uids, either invisible (ifoutputif specified) or visibly (if not).
Examples
### Simple examplerock::prepend_ids_to_source( "brief\nexample\nsource");### Example including fake YAML fragmentslongerExampleText <- c( "---", "First YAML fragment", "---", "So this is an utterance (i.e. outside of YAML)", "This, too.", "---", "Second fragment", "---", "Another real utterance outside of YAML", "Another one outside", "Last 'real utterance'" );rock::prepend_ids_to_source( longerExampleText);Prepend a line with a TSSID to a source
Description
This function adds a line with a TSSID (a time-stamped source identifier)to the beginning of a source that was read with one oftheloading_sources functions. When combined with UIDs, TSSIDs arevirtually unique references to a specific data fragment.
Usage
prepend_tssid_to_source( input, moment = format(Sys.time(), "%Y-%m-%d %H:%M"), output = NULL, designationSymbol = "=", preventOverwriting = rock::opts$get("preventOverwriting"), rlWarn = rock::opts$get(rlWarn), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | The source, as produced by one of the |
moment | Optionally, the moment as a character value of the form |
output | If specified, the coded source will be written here. |
designationSymbol | The symbol to use to designate an instanceidentifier for a class (can be " |
preventOverwriting | Whether to prevent overwriting existing files. |
rlWarn | Whether to let |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Details
TSSIDs are a date and time in the UTC timezone, consisting of eight digits(four for the year, two for the month, and two for the day), aT, fourdigits (two for the hour and two for the minute), and aZ (to designatethat the time is specified in the UTC timezone). TSSIDs are valid ISO8601standard date/times.
Value
Invisibly, the coded source object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Parse single example sourceloadedExample <- rock::load_source(exampleFile);### Add a coder identifierloadedExample <- rock::prepend_tssid_to_source( loadedExample, moment = "2025-05-28 11:30 CEST" );### Show the first linecat(loadedExample[1]);Efficiently preprocess data
Description
Efficiently preprocess data
Usage
preprocess_source( input, output = NULL, clean = TRUE, cleaningArgs = NULL, wordwrap = TRUE, wrappingArgs = NULL, prependUIDs = TRUE, UIDArgs = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), rlWarn = rock::opts$get("rlWarn"), silent = rock::opts$get("silent"))Arguments
input | The source |
output | For |
clean | Whether to clean |
cleaningArgs | Arguments to use for cleaning |
wordwrap | Whether to wordwrap |
wrappingArgs | Arguments to use for word wrapping |
prependUIDs | Whether to prepend UIDs |
UIDArgs | Arguments to use for prepending UIDs |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding of the source(s). |
rlWarn | Whether to let |
silent | Whether to suppress the warning about not editing the cleaned source. |
Value
The preprocessed source as character vector.
Examples
exampleText <- paste0( "Lorem ipsum dolor sit amet, consectetur ", "adipiscing elit. Nunc non commodo ex, ac ", "varius mi. Praesent feugiat nunc eget urna ", "euismod lobortis. Sed hendrerit suscipit ", "nisl, ac tempus magna porta et. ", "Quisque libero massa, tempus vel tristique ", "lacinia, tristique in nulla. Nam cursus enim ", "dui, non ornare est tempor eu. Vivamus et massa ", "consectetur, tristique magna eget, viverra elit." );### Show example textcat(exampleText);### Show preprocessed example textrock::preprocess_source( exampleText);Initialize a (pre)registration
Description
To initialize a (pre)registration, pass the URL to a Google Sheet holdingthe (pre)registration form specification (in {preregr} format), see the"Creating a form from a spreadsheet"vignette), the path to a file with a spreadsheet holding such aspecification, or a loaded or imported {preregr} (pre)registration form.
Usage
prereg_initialize(x, initialText = "Unspecified")Arguments
x | The (pre)registration form specification, as a URL to a GoogleSheet or online file or as the path to a locally stored file. |
initialText | The text to initialize every field with. |
Details
For an introduction to working with {preregr} (pre)registrations,see the"Specifying preregistration content"vignette.
Value
The empty (pre)registration specification.
Examples
rock::prereg_initialize( "preregQE_v0_95");Prettify a source in HTML
Description
This function adds HTML tags to a source to allow pretty printing/viewing.For an example, visithttps://rock.opens.science/articles/rock.html.
Usage
prettify_source( x, heading = NULL, headingLevel = 2, add_html_tags = TRUE, output = NULL, outputViewer = "viewer", template = "default", includeCSS = TRUE, preserveSpaces = TRUE, includeBootstrap = rock::opts$get("includeBootstrap"), preventOverwriting = rock::opts$get(preventOverwriting), silent = rock::opts$get(silent))Arguments
x | The source, as imported with |
heading | Optionally, a title to include in the output. The titlewill be prefixed with |
headingLevel | The number of hashes to insert before the headings. |
add_html_tags | Whether to add HTML tags to the result. |
output | Here, a path and filename can be provided where theresult will be written. If provided, the result will be returnedinvisibly. |
outputViewer | If showing output, where to show the output: inthe console ( |
template | The template to load; either the name of oneof the ROCK templates (currently, only 'default' is available), orthe path and filename of a CSS file. |
includeCSS | Whether to include the ROCK CSS in the returned HTML. |
preserveSpaces | Whether to preservce spaces (by replacing every secondspace with |
includeBootstrap | Whether to include the default bootstrap CSS. |
preventOverwriting | Whether to prevent overwriting of output files. |
silent | Whether to provide ( |
Value
A character vector with the prettified source
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Prettify source; if using RStudio, by default the### prettified source is shown in the viewer. You can### view the output of this example in the "rock" vignette### at https://rock.opens.science/articles/rock.htmlrock::prettify_source( exampleFile);Plot the graphs in a list of graphs
Description
Plot the graphs in a list of graphs
Usage
## S3 method for class 'rock_graphList'print(x, ...)Arguments
x | The list of graphs |
... | Any other arguments are passed to |
Value
x, invisibly
Convert a QNA network to Linear Topic Map format
Description
The Linear Topic Map format, LTM (https://ontopia.net/download/ltm.html),allows specification of networks in a human-readable format.
Usage
qna_to_tlm( x, topicmapId = "rock_qna_topicmap", topicmapTitle = "A ROCK QNA Topic Map")Arguments
x | The parsed source object (as produced by |
topicmapId,topicmapTitle | The topic map's identifier and title. |
Value
Ifx is a single parsed source: a character vector holding theLinear Topic Map specification; or, if multiple network coding schemes wereused in parallel, each in a list. Ifx contains multiple parseds sources,a list of such objects (i.e., a list of vectors, or a list of lists ofvectors).
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Read a souce coded with the Qualitative Network ApproachqnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) );### Convert and show the topic mapcat( rock::qna_to_tlm( qnaExample ), sep="\n");Qualitative/Unified Exploration of State Transitions
Description
Qualitative/Unified Exploration of State Transitions
Usage
quest( x, rawClassIdentifierCol = "state_raw", labelFun = base::round, labelFunArgs = list(digits = 2))Arguments
x | A parsed source document as provided by |
rawClassIdentifierCol | The identifier of the column in |
labelFun | A function to apply to the edge labels in preprocessing. |
labelFunArgs | Arguments to specify to |
Value
ADiagrammeR::grViz() object, which will print to show theQUEST graph.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "state-example-1.rock");### Parse single example sourceparsedExample <- rock::parse_source(exampleFile);### Show a QUEST graphrock::quest( parsedExample);Bind lots of dataframes together rowwise
Description
Bind lots of dataframes together rowwise
Usage
rbind_df_list(x)Arguments
x | A list of dataframes |
Value
A dataframe
Examples
rbind_df_list(list(Orange, mtcars, ChickWeight));Simple alternative for rbind.fill or bind_rows
Description
Simple alternative for rbind.fill or bind_rows
Usage
rbind_dfs(x, y, clearRowNames = TRUE)Arguments
x | One dataframe |
y | Another dataframe |
clearRowNames | Whether to clear row names (to avoid duplication) |
Value
The merged dataframe
Examples
rbind_dfs(Orange, mtcars);Convenience function to read spreadsheet-like files
Description
Currently reads spreadsheets from Google Sheets or fromxlsx,csv,orsav files.
Usage
read_spreadsheet( x, sheet = NULL, columnDictionary = NULL, localBackup = NULL, exportGoogleSheet = FALSE, flattenSingleDf = FALSE, xlsxPkg = c("rw_xl", "openxlsx", "XLConnect"), failQuietly = FALSE, silent = rock::opts$get("silent"))Arguments
x | The URL or path to a file. |
sheet | Optionally, the name(s) of the worksheet(s) to select. |
columnDictionary | Optionally, a dictionary with column names tocheck for presence. A named list of vectors. |
localBackup | If not |
exportGoogleSheet | If |
flattenSingleDf | Whether to return the result as a data frame ifonly one data frame is returned as a result. |
xlsxPkg | Which package to use to work with Excel spreadsheets. |
failQuietly | Whether to give an error when |
silent | Whether to be silent or chatty. |
Value
A list of dataframes, or, if only one data frame was loaded andflattenSingleDf isTRUE, a data frame.
Examples
### Note that this will require an active### internet connection! This if statement### checks for that.if (tryCatch({readLines("https://google.com",n=1); TRUE}, error=function(x) FALSE)) { ### Read the example ROCK codebook ROCK_codebook <- read_spreadsheet( paste0( "https://docs.google.com/spreadsheets/d/", "1gVx5uhYzqcTH6Jq7AYmsLvHSBaYaT-23c7ZhZF4jmps" ) ); ### Show a bit ROCK_codebook$metadata[1:3, ];}Add child codes under a parent code
Description
This function conditionally adds new child codes under a code. Whererecode_split() removes the original code (splittingit into the new codes), this function retains the original, adding the newcodes as sub-codes.
Usage
recode_addChildCodes( input, codes, childCodes, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_rcAdded", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A single character value with the code to add the child codesto. |
childCodes | A named list with specifying when to add whichchild code. Each element of this list is a filtering criterion that will bepassed on to |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the changed source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExampleSource <- rock::load_source(exampleFile);### Split a code into two codes, showing progress (the backticks are### used to be able to specify a name that starts with an underscore)recoded_source <- rock::recode_addChildCodes( loadedExampleSource, codes="childCode1", childCodes = list( `_and_` = " and ", `_book_` = "book", `_else_` = TRUE ), silent=FALSE );Remove one or more codes
Description
These functions remove one or more codes from a source, and make it easy tojustify that decision.
Usage
recode_delete( input, codes, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_rcDeleted", childrenReplaceParents = TRUE, recursiveDeletion = FALSE, decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A character vector with codes to remove. |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
childrenReplaceParents | Whether children should be deleted ( |
recursiveDeletion | Whether to also delete a code's parents ( |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the recoded source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Delete two codes, moving children to the codes' parentsrecoded_source <- rock::recode_delete( loadedExample, codes=c("childCode2", "childCode1"), silent=FALSE );### Process an entire directorylist_of_recoded_sources <- rock::recode_delete( examplePath, codes=c("childCode2", "childCode1"), silent=FALSE );Merge two or more codes
Description
This function merges two or more codes into one.
Usage
recode_merge( input, codes, mergeToCode, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_rcMerged", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A character vector with the codes to merge. |
mergeToCode | A single character vector with the merged code. |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the changed source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Move two codes to a new parent, showing progressrecoded_source <- rock::recode_merge( loadedExample, codes=c("childCode2", "grandchildCode2"), mergeToCode="mergedCode", silent=FALSE );Move one or more codes to a different parent
Description
These functions move a code to a different parent (and therefore,ancestry) in one or more sources.
Usage
recode_move( input, codes, newAncestry, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_rcMoved", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A character vector with codes to move. |
newAncestry | The new parent code, optionally including the partialor full ancestry (i.e. the path of parent codes all the way up to the root). |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the changed source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Move two codes to a new parent, showing progressrecoded_source <- rock::recode_move( loadedExample, codes=c("childCode2", "childCode1"), newAncestry = "parentCode2", silent=FALSE );Rename one or more codes
Description
These functions rename one or more codes in one or more sources.
Usage
recode_rename( input, codes, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_rcRenamed", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A named character vector with codes to rename. Each elementshould be the new code, and the element's name should be the old code (soe.g. |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the changed source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Move two codes to a new parent, showing progressrecoded_source <- rock::recode_rename( loadedExample, codes=c(childCode2 = "grownUpCode2", grandchildCode2 = "almostChildCode2"), silent=FALSE );Split a code into multiple codes
Description
This function conditionally splits a code into multiple codes. Note that youmay want to userecode_addChildCodes() instead to not lose theoriginal coding.
Usage
recode_split( input, codes, splitToCodes, filter = TRUE, output = NULL, filenameRegex = ".*", outputPrefix = "", outputSuffix = "_recoded", decisionLabel = NULL, justification = NULL, justificationFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
input | One of 1) a character string specifying the path to a filewith a source; 2) an object with a loaded source as produced by a callto |
codes | A single character value with the code to split. |
splitToCodes | A named list with specifying when to split to whichnew code. Each element of this list is a filtering criterion that will bepassed on to |
filter | Optionally, a filter to apply to specify a subset of thesource(s) to process (see |
output | If specified, the recoded source(s) will be written here. |
filenameRegex | Only process files matching this regular expression. |
outputPrefix,outputSuffix | The prefix and suffix to add to thefilenames when writing the processed files to disk, in case multiplesources are passed as input. |
decisionLabel | A description of the (recoding) decision that was taken. |
justification | The justification for this action. |
justificationFile | If specified, the justification is appended tothis file. If not, it is saved to the |
preventOverwriting | Whether to prevent overwriting existing fileswhen writing the files to |
encoding | The encoding to use. |
silent | Whether to be chatty or quiet. |
Value
Invisibly, the changed source(s) or source(s) object.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Split a code into two codes, showing progressrecoded_source <- rock::recode_split( loadedExample, codes="childCode1", splitToCodes = list( and_REPLACED = " and ", book_REPLACED = "book", else_REPLACED = TRUE ), silent=FALSE );Repeat a string a number of times
Description
Repeat a string a number of times
Usage
repeatStr(n = 1, str = " ")Arguments
n,str | Normally, respectively the frequency with which torepeat the string and the string to repeat; but the order of theinputs can be switched as well. |
Value
A character vector of length 1.
Examples
### 10 spaces:repStr(10);### Three euro symbols:repStr("\u20ac", 3);Show all coded fragments
Description
Show all coded fragments
Usage
resultsOverview_allCodedFragments( x, root = "codes", context = 0, heading = NULL, headingLevel = 2, add_html_tags = TRUE, cleanUtterances = FALSE, output = NULL, outputViewer = "viewer", template = "default", includeCSS = TRUE, includeBootstrap = rock::opts$get("includeBootstrap"), preventOverwriting = rock::opts$get(preventOverwriting), silent = rock::opts$get(silent))Arguments
x | The parsed source(s) as provided by |
root | The root code |
context | How many utterances before and after the targetutterances to include in the fragments. If two values, the first is thenumber of utterances before, and the second, the number of utterancesafter the target utterances. |
heading | Optionally, a title to include in the output. The titlewill be prefixed with |
headingLevel | The number of hashes to insert before the headings. |
add_html_tags | Whether to add HTML tags to the result. |
cleanUtterances | Whether to use the clean or the raw utteranceswhen constructing the fragments (the raw versions contain all codes). Note thatthis should be set to |
output | Here, a path and filename can be provided where theresult will be written. If provided, the result will be returnedinvisibly. |
outputViewer | If showing output, where to show the output: inthe console ( |
template | The template to load; either the name of oneof the ROCK templates (currently, only 'default' is available), orthe path and filename of a CSS file. |
includeCSS | Whether to include the ROCK CSS in the returned HTML. |
includeBootstrap | Whether to include the default bootstrap CSS. |
preventOverwriting | Whether to prevent overwriting of output files. |
silent | Whether to provide ( |
Value
Invisibly, the coded fragments in a character vector.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path( examplePath, "example-1.rock" );### Parse single example sourceparsedExample <- rock::parse_source( exampleFile );### Show organised coded fragments in Markdowncat( rock::resultsOverview_allCodedFragments( parsedExample ));Get the roots from a vector with code paths
Description
Get the roots from a vector with code paths
Usage
root_from_codePaths(x)Arguments
x | A vector of code paths. |
Value
A vector with the root of each element.
Examples
root_from_codePaths( c("codes>reason>parent_feels", "codes>reason>child_feels"));Create a source with items to code for Response Process Evaluation
Description
This function creates a plain text file, a.rock source, that can becoded when conducting Response Process Evaluation.
Usage
rpe_create_source_with_items( data, iterationId, batchId, populationId, itemVarNames, metaquestionIdentifiers, metaquestionVarNames, itemContents, metaquestionContents, coderId, caseIds = NULL, outputFile = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get("encoding"), silent = rock::opts$get("silent"))Arguments
data | A (wide) data frame containing at least the participants'answers to the items and to the meta questions (but optionally, theiteration, batch, and population). |
iterationId,batchId,populationId | If the iteration, batch, andpopulation identifiers are contained in the data frame passed as |
itemVarNames | The variable names with the participants' responsesto the items, in a named character vector, with each element's name beingthe item's identifier, and each element the variable name in |
metaquestionIdentifiers | A named list of unnamed character vectors,with each character vector element specifying the identifier of a metaquestion, and each list element (i.e. the name of each character vector)specifying the item identifier that the meta questions in the correspondingcharacter vector belong to. |
metaquestionVarNames | The variable names with the participants'responses to the meta questions, in a named character vector, with eachelement's name being the meta question's identifier, and each elementthe variable name in |
itemContents | A named character vector with each item's content, withthe values being the content and the names the item identifiers. |
metaquestionContents | A named character vector with each metaquestion's content, with the values being the content and the names themeta question identifiers. |
coderId | The identifier of the coder that will code this source. |
caseIds | The variable name with the participants' case identifiers (i.e.a unique identifier for each participant). |
outputFile | Optionally, a file to write the source to. |
preventOverwriting | Whether to overwrite existing files ( |
encoding | The encoding to use when writing the source(s). |
silent | Whether to the silent ( |
Value
The created source, as a character vector (invisibly);
Save your justifications to a file
Description
When conducting analyses, you make many choices that ideally, youdocument and justify. This function saves stored justifications to afile.
Usage
save_workspace( file = rock::opts$get("justificationFile"), encoding = rock::opts$get("encoding"), append = FALSE, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
file | If specified, the file to export the justification to. |
encoding | The encoding to use when writing the file. |
append | Whether to append to the file, or replace its contents. |
preventOverwriting | Whether to prevent overwriting an existing file. |
silent | Whether to be silent or chatty. |
Value
The result of a call tojustifier::export_justification().
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::load_source(exampleFile);### Split a code into two codes, showing progress (the backticks are### used to be able to specify a name that starts with an underscore)recoded_source <- rock::recode_split( loadedExample, codes="childCode1", splitToCodes = list( `_and_` = " and ", `_book_` = "book", `_else_` = TRUE ), silent=FALSE, justification = "Because this seems like a good idea" );### Save this workspace to a filetemporaryFilename <- tempfile();rock::save_workspace(file = temporaryFilename);Show a table with all attributes in the RStudio viewer and/or console
Description
Show a table with all attributes in the RStudio viewer and/or console
Usage
show_attribute_table( x, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS"))Arguments
x | A |
output | The output: a character vector with one or moreof " |
tableOutputCSS | The CSS to use for the HTML table. |
Value
x, invisibly, unless being knitted into R Markdown,in which case aknitr::asis_output()-wrapped character vector is returned.
Show the fully merged code tree(s)
Description
Show the fully merged code tree(s)
Usage
show_fullyMergedCodeTrees(x)Arguments
x | A parsed source(s) object. |
Value
The result of a call toDiagrammeR::render_graph().
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);### Show merged code treeshow_fullyMergedCodeTrees(loadedExample);Show the inductive code tree(s)
Description
This function shows one or more inductive code trees.
Usage
show_inductive_code_tree( x, codes = ".*", output = "both", headingLevel = 3, nodeStyle = list(shape = "box", fontname = "Arial"), edgeStyle = list(arrowhead = "none"), graphStyle = list(rankdir = "LR"))Arguments
x | A |
codes | A regular expression: only code trees from codes codedwith a coding pattern with this name will be shown. |
output | Whether to show the code tree in the console ( |
headingLevel | The level of the heading to insert when showing thecode tree as text. |
nodeStyle,edgeStyle,graphStyle | Arguments to pass on to,respectively, |
Value
x, invisibly, unless being knitted into R Markdown,in which case aknitr::asis_output()-wrapped character vector is returned.
Soft Non-numeric Occurrence Estimation (SNOE) plot
Description
Soft Non-numeric Occurrence Estimation (SNOE) plot
Usage
snoe_plot( x, codes = ".*", matchRegexAgainstPaths = TRUE, estimateWithin = NULL, title = "SNOE plot", ggplot2Theme = ggplot2::theme_minimal(), greyScale = FALSE, colors = c("#0072B2", "#C0C0C0"), greyScaleColors = c("#808080", "#C0C0C0"), silent = rock::opts$get("silent"))Arguments
x | A parsed source(s) object. |
codes | A regular expression to select codes to include, or,alternatively, a character vector with literal code idenfitiers. |
matchRegexAgainstPaths | Whether to match the |
estimateWithin | The column specifying within what to count. |
title | Title of the plot |
ggplot2Theme | Can be used to specify theme elements for the plot. |
greyScale | Whether to produce the plot in color ( |
colors,greyScaleColors | The (two) colors to use for the color andgreyscale versions of the SNOE plot. |
silent | Whether to be chatty or silent |
Value
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-3.rock");### Load example sourceloadedExample <- rock::parse_source(exampleFile);### Show code occurrence estimatesrock::snoe_plot( loadedExample);### Load two example sourcesloadedExamples <- rock::parse_sources( examplePath, regex = "example-[34].rock");rock::snoe_plot( loadedExamples);Split long lines
Description
This function splits long lines at a given number of characters,keeping words intact. It's basically a wrapper aroundstrwrap().
Usage
split_long_lines( x, length = 60, collapseResult = FALSE, splitString = rock::opts$get("utteranceMarker"))Arguments
x | The string (e.g. a source) |
length | The maximum length |
collapseResult | Whether to collapse the result from a vector (withline breaks separating the elements) to a single character value (wherethe vector elements are glued together using |
splitString | The character to use to split lines. |
Value
A character vector.
Examples
cat( rock::split_long_lines( paste0( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. ", "Vestibulum et dictum urna. Donec neque nunc, lacinia vitae ", "varius vitae, pretium quis nibh. Aliquam pulvinar, lacus ", "sed varius vulputate, justo nibh blandit quam, ", "nec sollicitudin velit augue eget erat." ) ));Strip the root from a code path
Description
This function strips the root (just the first element) from a code path,using thecodeTreeMarker stored in theopts object as marker.
Usage
stripCodePathRoot(x)Arguments
x | A vector of code paths. |
Value
The modified vector of code paths.
Examples
stripCodePathRoot("codes>reason>parent_feels");Synchronize multiple streams
Description
This function maps the codes from multiple streams onto a primary stream.
Usage
sync_streams( x, primaryStream, columns = NULL, anchorsCol = rock::opts$get("anchorsCol"), sourceId = rock::opts$get("sourceId"), streamId = rock::opts$get("streamId"), prependStreamIdToColName = FALSE, appendStreamIdToColName = TRUE, sep = " ", fill = TRUE, paddingValue = NA, neverFill = grep("_raw$", names(x$qdt), value = TRUE), compressFun = NULL, compressFunPart = NULL, expandFun = NULL, carryOverAnchors = FALSE, colNameGlue = rock::opts$get("colNameGlue"), silent = rock::opts$get("silent"))Arguments
x | The object with the parsed sources. |
primaryStream | The identifier of the primary stream. |
columns | The names of the column(s) to synchronize. |
anchorsCol | The column containing the anchors. |
sourceId | The column containing the source identifiers. |
streamId | The column containing the stream identifiers. |
prependStreamIdToColName,appendStreamIdToColName | Whether to appendor prepend the stream identifier before merging the dataframes together. |
sep | When not specifying |
fill | When expanding streams, whether to duplicate elements to fillthe resulting vector. Ignored if |
paddingValue | The value to insert for rows when not filling (bydefault, filling carries over the value from the last preceding row thathad a value specified). |
neverFill | Columns to never fill regardless of whether fillis |
compressFun | If specified, when compressing streams, instead of pastingelements together using separator |
compressFunPart | A function to apply to the segments that areautomatically created; this can be passed instead of |
expandFun | If specified, when expanding streams, instead of potentiallyfilling the new larger vector with elements (if |
carryOverAnchors | Whether to carry over anchors for each source |
colNameGlue | When appending or prepending stream identifiers, thecharacter(s) to use as "glue" or separator. |
silent | Whether to be silent ( |
Value
The object with parsd sources,x, with the synchronization resultsadded in the$syncResults subobject.
Examples
### Get a directory with example sourcesexamplePath <- file.path( system.file(package="rock"), 'extdata', 'streams' );### Parse the sourcesparsedSources <- rock::parse_sources( examplePath);### Add a dataframe, syncing all streams to primary stream !parsedSources <- rock::sync_streams( parsedSources, primaryStream = "streamA", columns = c("Code1", "Code2", "Code3"), prependStreamIdToColName = TRUE);### Look at two examplesparsedSources$syncResults$qdt[ , c("streamB_Code3_streamB", "streamC_Code1_streamC")];Sync (expand or compress) a vector
Description
Sync (expand or compress) a vector
Usage
sync_vector( x, newLength, sep = " ", fill = TRUE, compressFun = NULL, expandFun = NULL, compressFunPart = NULL, silent = rock::opts$get("silent"))Arguments
x | The vector |
newLength | The new length |
sep | When not specifying |
fill | When expanding streams, whether to duplicate elements to fillthe resulting vector. Ignored if |
compressFun | If specified, when compressing streams, instead of pastingelements together using separator |
expandFun | If specified, when expanding streams, instead of potentiallyfilling the new larger vector with elements (if |
compressFunPart | A function to apply to the segments that areautomatically created; this can be passed instead of |
silent | Whether to be silent or chatty. |
Value
The synced vector
Examples
rock::sync_vector(letters[1:10], 15);rock::sync_vector(letters[1:10], 5);Compress a vector or data frame
Description
Compress a vector or data frame
Usage
syncing_df_compress( x, newLength, sep = " ", compressFun = NULL, compressFunPart = NULL, silent = rock::opts$get("silent"))syncing_vector_compress( x, newLength, sep = " ", compressFun = NULL, compressFunPart = NULL, silent = rock::opts$get("silent"))Arguments
x | The vector or data frame |
newLength | The new length (or number of rows for a data frame) |
sep | When not specifying |
compressFun | If specified, when compressing streams, instead of pastingelements together using separator |
compressFunPart | A function to apply to the segments that areautomatically created; this can be passed instead of |
silent | Whether to be silent or chatty. |
Value
The compressed vector or data frame
Examples
rock::syncing_vector_compress( 1:10, 3);rock::syncing_df_compress( mtcars[, 1:4], 6);rock::syncing_df_compress( mtcars[, 1:4], 6, compressFunPart = mean);Expand a vector or data frame
Description
Expand a vector or data frame
Usage
syncing_df_expand( x, newLength, fill = TRUE, neverFill = NULL, paddingValue = NA, expandFun = NULL, silent = rock::opts$get("silent"))syncing_vector_expand( x, newLength, fill = TRUE, paddingValue = NA, expandFun = NULL, silent = rock::opts$get("silent"))Arguments
x | The vector or data frame |
newLength | The new length (or number of rows for a data frame) |
fill | When expanding streams, whether to duplicate elements to fillthe resulting vector. Ignored if |
neverFill | Columns to never fill regardless of whether fill is |
paddingValue | The value to insert for rows when not filling (bydefault, filling carries over the value from the last preceding row thathad a value specified). |
expandFun | If specified, when expanding streams, instead of potentiallyfilling the new larger vector with elements (if |
silent | Whether to be silent or chatty. |
Value
The expanded vector
Examples
rock::syncing_vector_expand(letters[1:10], 15);rock::syncing_vector_expand(letters[1:10], 15, fill=FALSE);Create a templated report for cognitive interviews
Description
Use this function to export a templated report for cognitive interviews.To embed it in an R Markdown file, use!!! CREATE rock::knit_codebook() !!!
Usage
template_ci_heatmap_1_to_pdf( x, file, title = "Cognitive Interview: Heatmap and Coded Fragments", author = NULL, caption = "Heatmap", headingLevel = 1, silent = rock::opts$get("silent"))Arguments
x | The codebook object (as produced by a call to |
file | The filename to save the codebook to. |
title | The title to use. |
author | The author to specify in the PDF. |
caption | The caption for the heatmap. |
headingLevel | The level of the top-most headings. |
silent | Whether to be silent or chatty. |
Value
x, invisibly
Examples
### Use a temporary file to write totmpFile <- tempfile(fileext = ".pdf");### Load an example CIexamplePath <- file.path(system.file(package="rock"), 'extdata');parsedCI <- parse_source(file.path(examplePath, "ci_example_1.rock"));rock::template_ci_heatmap_1_to_pdf( parsedCI, file = tmpFile);Convert a codebook specification to PDF
Description
Use this function to export your codebook specification to a PDFfile. To embed it in an R Markdown file, use!!! CREATE rock::knit_codebook() !!!
Usage
template_codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent"))Arguments
x | The codebook object (as produced by a call to |
file | The filename to save the codebook to. |
author | The author to specify in the PDF. |
headingLevel | The level of the top-most headings. |
silent | Whether to be silent or chatty. |
Value
x, invisibly
Examples
### Use a temporary file to write totmpFile <- tempfile(fileext = ".pdf");### Load an example codebookdata("exampleCodebook_1", package = "rock");rock::template_codebook_to_pdf( exampleCodebook_1, file = tmpFile);Easily parse a vector into a character value
Description
Easily parse a vector into a character value
Usage
vecTxt( vector, delimiter = ", ", useQuote = "", firstDelimiter = NULL, lastDelimiter = " & ", firstElements = 0, lastElements = 1, lastHasPrecedence = TRUE)vecTxtQ(vector, useQuote = "'", ...)Arguments
vector | The vector to process. |
delimiter,firstDelimiter,lastDelimiter | The delimitersto use for respectively the middle, first |
useQuote | This character string is pre- and appended to all elements;so use this to quote all elements ( |
firstElements,lastElements | The number of elements for which to usethe first respective last delimiters |
lastHasPrecedence | If the vector is very short, it's possible that thesum of firstElements and lastElements is larger than the vector length. Inthat case, downwardly adjust the number of elements to separate with thefirst delimiter ( |
... | Any addition arguments to |
Value
A character vector of length 1.
Examples
vecTxtQ(names(mtcars));Wordwrapping a source
Description
This function wordwraps a source.
Usage
wordwrap_source( input, output = NULL, length = 40, removeNewlines = FALSE, removeTrailingNewlines = TRUE, rlWarn = rock::opts$get(rlWarn), preventOverwriting = rock::opts$get("preventOverwriting"), encoding = rock::opts$get(encoding), silent = rock::opts$get(silent), utteranceMarker = rock::opts$get("utteranceMarker"))Arguments
input | For |
output | For |
length | At how many characters to word wrap. |
removeNewlines | Whether to remove all newline characters from the source beforestarting to clean them.Be careful: if the source contains YAML fragments, thesewill also be affected by this, and will probably become invalid! |
removeTrailingNewlines | Whether to remove trailing newline characters(i.e. at the end of a character value in a character vector); |
rlWarn | Whether to let |
preventOverwriting | Whether to prevent overwriting of output files. |
encoding | The encoding of the source(s). |
silent | Whether to suppress the warning about not editing the cleaned source. |
utteranceMarker | The character(s) between utterances (i.e. marking whereone utterance ends and the next one starts). By default, this is a linebreak, and only change this if you know what you are doing. |
Value
A character vector.
Examples
exampleText <- paste0( "Lorem ipsum dolor sit amet, consectetur ", "adipiscing elit. Nunc non commodo ex, ac ", "varius mi. Praesent feugiat nunc eget urna ", "euismod lobortis. Sed hendrerit suscipit ", "nisl, ac tempus magna porta et. ", "Quisque libero massa, tempus vel tristique ", "lacinia, tristique in nulla. Nam cursus enim ", "dui, non ornare est tempor eu. Vivamus et massa ", "consectetur, tristique magna eget, viverra elit." );### Show example textcat(exampleText);### Show preprocessed example textcat( paste0( rock::wordwrap_source( exampleText ), collapse = "\n" ));Wrap all elements in a vector
Description
Wrap all elements in a vector
Usage
wrapVector(x, width = 0.9 * getOption("width"), sep = "\n", ...)Arguments
x | The character vector |
width | The number of |
sep | The glue with which to combine the new lines |
... | Other arguments are passed to |
Value
A character vector
Examples
res <- wrapVector( c( "This is a sentence ready for wrapping", "So is this one, although it's a bit longer" ), width = 10);print(res);cat(res, sep="\n");Write a source to a file
Description
These functions write one or more source(s) from memory (asloaded byload_source() orload_sources() to a file.
Usage
write_source( x, output, encoding = rock::opts$get("encoding"), preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))write_sources( x, output, filenamePrefix = "", filenameSuffix = "_written", recursive = TRUE, encoding = rock::opts$get("encoding"), preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent"))Arguments
x | The source(s). |
output | The filename (for |
encoding | The encoding to use. |
preventOverwriting | Whether to prevent against overwriting of thefile(s) to write. Set to |
silent | Whether to be chatty or quiet. |
filenamePrefix,filenameSuffix | Optional prefixes or suffixes to pre-or append to the filenames when writing the files. |
recursive | Whether to recursively create directories if the |
Value
Invisibly, the input (x), to enable chaining in pipes.
Examples
### Get path to example sourceexamplePath <- system.file("extdata", package="rock");### Get a path to one example fileexampleFile <- file.path(examplePath, "example-1.rock");### Get a temporary file to write totempFile <- tempfile(fileext = ".rock")### For R versions below 4.1loadedSource <- rock::load_source(exampleFile);loadedSource <- rock::code_source( loadedSource, c("Lorem Ipsum" = "lorumIpsum") );rock::write_source( loadedSource, tempFile);### From R 4.1 onwards, you can also chain### these commands using the pipe operator.###### Note that that means that this example### will not run if you have a previous### version of R.loadedSource <- rock::load_source(exampleFile) |> rock::code_source(c("Lorem Ipsum" = "lorumIpsum")) |> rock::write_source(tempFile);Get indices of YAML delimiters
Description
Get indices of YAML delimiters
Usage
yaml_delimiter_indices(x)Arguments
x | The character vector. |
Value
A numeric vector.
Examples
yaml_delimiter_indices( c("not here", "---", "above this one", "but nothing here", "below this one, too", "---"));### [1] 2 6