| Title: | Reproducible Open Coding Kit |
|---|---|
| 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 at <https://rock.science>. |
| Authors: | Gjalt-Jorn Peters [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-0336-9589>), Szilvia Zörgő [aut] (ORCID: <https://orcid.org/0000-0002-6916-2097>) |
| Maintainer: | Gjalt-Jorn Peters <[email protected]> |
| License: | GPL-3 |
| Version: | 0.9.6 |
| Built: | 2026-05-09 06:02:42 UTC |
| Source: | https://github.com/cran/rock |
This function adds HTML tags to a source to allow pretty printing/viewing.
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") )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") )
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 case
identifiers or coder identifiers), section breaks, utterance
identifiers, context, full utterances, comments, network codes, source lines, codings, and YAML chunks. All |
The character vector with the replacements made.
### Add tags to a mini example source add_html_tags("[[cid=participant1]] This is something this participant may have said. Just like this. [[thisIsACode]] ---paragraph-break--- And another utterance.");### Add tags to a mini example source add_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
apply_graph_theme(graph, ...)apply_graph_theme(graph, ...)
graph |
The DiagrammeR::DiagrammeR graph to apply the attributes to. |
... |
One or more character vectors of length three, where the first element is
the attribute, the second the value, and the third, the attribute type ( |
The DiagrammeR::DiagrammeR graph.
### Create an example source exampleSource <- ' --- codes: - id: parentCode label: Parent code children: - id: childCode1 - id: childCode2 - id: childCode3 label: Child Code parentId: parentCode children: [grandChild1, grandChild2] --- '; ### Parse it parsedSource <- rock::parse_source( text = exampleSource ); ### Extract the deductive code tree from ### the parsed source deductiveCodeTree <- parsedSource$deductiveCodeTrees; ### Convert it to a DiagrammeR graph miniGraph <- data.tree::ToDiagrammeRGraph( deductiveCodeTree ); ### Show the graph DiagrammeR::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 graph DiagrammeR::render_graph( miniGraph_themed );### Create an example source exampleSource <- ' --- codes: - id: parentCode label: Parent code children: - id: childCode1 - id: childCode2 - id: childCode3 label: Child Code parentId: parentCode children: [grandChild1, grandChild2] --- '; ### Parse it parsedSource <- rock::parse_source( text = exampleSource ); ### Extract the deductive code tree from ### the parsed source deductiveCodeTree <- parsedSource$deductiveCodeTrees; ### Convert it to a DiagrammeR graph miniGraph <- data.tree::ToDiagrammeRGraph( deductiveCodeTree ); ### Show the graph DiagrammeR::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 graph DiagrammeR::render_graph( miniGraph_themed );
This function converts an object to a character vector and marks it as a ROCK source.
as.rock_source(x)as.rock_source(x)
x |
The source contents. |
A character vector with class rock_source.
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 );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 );
Note: this function is deprecated; use this function in the {squids}
package!
base30toNumeric(x) numericToBase30(x)base30toNumeric(x) numericToBase30(x)
x |
The vector to convert (numeric for |
The conversion functions from base10 to base30 and vice versa are
used by the generate_uids() functions.
The symbols to represent the 'base 30' system are the 0-9
followed by the alphabet without vowels but including the y (see
squids::squids-package).
The converted vector (numeric for base30toNumeric, character for numericToBase30).
rock::numericToBase30( 654321 ); rock::base30toNumeric( rock::numericToBase30( 654321 ) );rock::numericToBase30( 654321 ); rock::base30toNumeric( rock::numericToBase30( 654321 ) );
This function takes a value, and then replaces empty elements (NA or zero-length character values) with the last non-empty preceding element it encountered.
carry_over_values(x, noId = "no_id")carry_over_values(x, noId = "no_id")
x |
The vector |
noId |
The value to add for the first empty elements |
The vector with the carries over elements
rock::carry_over_values( c( NA, NA, 3, NA, NA, 7, NA, NA ) );rock::carry_over_values( c( NA, NA, 3, NA, NA, 7, NA, NA ) );
The cat0 function is to cat what paste0 is to paste; it simply makes concatenating many strings without a separator easier.
cat0(..., sep = "")cat0(..., sep = "")
... |
The character vector(s) to print; passed to cat. |
sep |
The separator to pass to cat, of course, |
Nothing (invisible NULL, like cat).
cat0("The first variable is '", names(mtcars)[1], "'.");cat0("The first variable is '", names(mtcars)[1], "'.");
This function efficiently checks for the presence of a package
without loading it (unlike library() or require().
This is useful to force yourself to use the package::function
syntax for addressing functions; you can make sure required packages
are installed, but their namespace won't attach to the search path.
checkPkgs( ..., install = FALSE, load = FALSE, repos = "https://cran.rstudio.com" )checkPkgs( ..., install = FALSE, load = FALSE, repos = "https://cran.rstudio.com" )
... |
A series of packages. If the packages are named, the names are the package names, and the values are the minimum required package versions (see the second example). |
install |
Whether to install missing packages from |
load |
Whether to load packages (which is exactly not the point of this package, but hey, YMMV). |
repos |
The repository to use if installing packages; default is the RStudio repository. |
Invisibly, a vector of the available packages.
rock::checkPkgs('base'); ### Require a specific version rock::checkPkgs(rock = "0.9.1"); ### This will show the error message tryCatch( rock::checkPkgs( base = "99", stats = "42.5", rock = 2000 ), error = print );rock::checkPkgs('base'); ### Require a specific version rock::checkPkgs(rock = "0.9.1"); ### This will show the error message tryCatch( rock::checkPkgs( base = "99", stats = "42.5", rock = 2000 ), error = print );
This function takes a Narrative Response Model specification as used in NRM-based cognitive interviews, and composes an item based on the specified template for that item, the specified stimuli, and the requested language.
ci_get_item(nrm_spec, item_id, language)ci_get_item(nrm_spec, item_id, language)
nrm_spec |
The Narrative Response Model specification. |
item_id |
The identifier of the requested item. |
language |
The language of the stimuli. |
A character value with the item.
When conducting cognitive interviews, it can be useful to quickly inspect the code distributions for each item. These heatmaps facilitate that process.
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() )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() )
x |
The object with the parsed coded source(s) as resulting from a
call to |
nrmSpec |
Optionally, an imported Narrative Response Model
specification, 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 instance
identifier prefix, e.g. if item identifiers are specified as
|
codingScheme |
The coding scheme, either as a string if it represents
one of the cognitive interviewig coding schemes provided with the |
itemlab, codelab, freqlab
|
Labels to use for the item and code axes
and 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 |
The heatmap as a ggplot2 plot.
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");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");
Narrative Response Models are a description of the theory of how a measurement instrument that measures a psychological construct works, geared towards conducting cognitive interviews to verify the validity of that measurement instrument. One a Narrative Response Model has been imported, it can be used to generate interview schemes, overview of each item's narrative response model, and combined with coded cognitive interview notes or transcripts.
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, ...)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, ...)
x |
A path to a file or an URL to a Google Sheet, passed
to |
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. |
A rock_ci_nrm object.
These functions can be used to 'clean' one or more sources or perform search and replace taks. Cleaning consists of two operations: splitting the source at utterance markers, and conducting search and replaces using regular expressions.
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") )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") )
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 for
in the source(s), and the second element contains the replacement (these are passed
as |
extraReplacementsPre, extraReplacementsPost
|
To perform more replacements
than the default set, these can be conveniently specified in |
removeNewlines |
Whether to remove all newline characters from the source before starting to clean them. Be careful: if the source contains YAML fragments, these will 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 to
insert breaks between utterances in the source(s). Such breakes are specified using
the |
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 the filenames when writing the processed files to disk. |
recursive |
Whether to search all subdirectories ( |
filenameRegex |
A regular expression to match against located files; only files 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 for
in the source(s), and the second element contains the replacement (these are passed
as |
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 periods
Three or more newline characters will be replaced by one newline character (which will become more, if the sentence before that character marks the end of an utterance)
All sentences will become separate utterances (in a semi-smart manner; specifically, breaks in speaking, if represented by three periods, are not considered 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.
A character vector for clean_source, or a list of character vectors,
for clean_sources.
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 fragment exampleWithYAML <- 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"))));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 fragment exampleWithYAML <- 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"))));
Utterance vectors are split by the utterance marker. Note that if x has
more than one element, the separate elements will remain separate.
cleaned_source_to_utterance_vector( x, utteranceMarker = rock::opts$get("utteranceMarker"), fixed = FALSE, perl = TRUE )cleaned_source_to_utterance_vector( x, utteranceMarker = rock::opts$get("utteranceMarker"), fixed = FALSE, perl = TRUE )
x |
The character vector. |
utteranceMarker |
The utterance marker (by default, a newline character conform the ROCK standard). |
fixed |
Whether the |
perl |
If the |
A character vector with separate utterances, split
by utteranceMarker.
cleaned_source_to_utterance_vector("first\nsecond\nthird");cleaned_source_to_utterance_vector("first\nsecond\nthird");
Code frequencies separate by a variable
code_freq_by(x, by, codes = ".*", returnTidyDf = FALSE)code_freq_by(x, by, codes = ".*", returnTidyDf = FALSE)
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 compute the code frequencies. |
returnTidyDf |
When |
A data frame with the code frequencies
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code frequencies code_freq_by(loadedExample, "nestingLevel");### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code frequencies code_freq_by(loadedExample, "nestingLevel");
Create a frequency histogram for codes
code_freq_hist( x, codes = ".*", sortByFreq = "decreasing", forceRootStripping = FALSE, trimSourceIdentifiers = 20, ggplot2Theme = ggplot2::theme(legend.position = "bottom"), silent = rock::opts$get("silent") )code_freq_hist( x, codes = ".*", sortByFreq = "decreasing", forceRootStripping = FALSE, trimSourceIdentifiers = 20, ggplot2Theme = ggplot2::theme(legend.position = "bottom"), silent = rock::opts$get("silent") )
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 are different. |
trimSourceIdentifiers |
If not |
ggplot2Theme |
Can be used to specify theme elements for the plot. |
silent |
Whether to be chatty or silent. |
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code frequencies code_freq_hist(loadedExample);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code frequencies code_freq_hist(loadedExample);
These functions add codes to one or more
sources that were read with one of the
loading_sources functions.
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") )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") )
input |
The source, or list of sources, as
produced by one of the |
codes |
A named character vector, where each element is the code to be added to the matching utterance, and the corresponding name is either an utterance identifier (in which case the utterance with that identifier will be coded with that code), a code (in which case all utterances with that code will be coded with the new code as well), a digit (in which case the utterance at that line number in the source will be coded with that code), or a regular expression, in which case all utterances matching that regular expression will be coded with that source. If specifying an utterance ID or code, make sure that the code delimiters are included (normally, two square brackets). |
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 to
this 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/or append to the filenames to distinguish them from the input filenames. |
recursive |
Whether to also read files from all subdirectories
of the |
filenameRegex |
Only input files matching this patterns will be read. |
Invisibly, the coded source object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Show line 71 cat(loadedExample[71]); ### Specify the rules to code all utterances ### containing "Ipsum" with the code 'ipsum' and ### all utterances containing the code codeSpecs <- c("(?i)ipsum" = "ipsum", "BC|AD|\\d\\d\\d\\ds" = "timeRef"); ### Apply rules codedExample <- code_source(loadedExample, codeSpecs); ### Show line 71 cat(codedExample[71]); ### Also add code "foo" to utterances with code 'ipsum' moreCodedExample <- code_source(codedExample, c("[[ipsum]]" = "foo")); ### Show line 71 cat(moreCodedExample[71]); ### Use the 'indices' argument to add the code 'bar' to ### line 71 overCodedExample <- code_source(moreCodedExample, "bar", indices=71); cat(overCodedExample[71]);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Show line 71 cat(loadedExample[71]); ### Specify the rules to code all utterances ### containing "Ipsum" with the code 'ipsum' and ### all utterances containing the code codeSpecs <- c("(?i)ipsum" = "ipsum", "BC|AD|\\d\\d\\d\\ds" = "timeRef"); ### Apply rules codedExample <- code_source(loadedExample, codeSpecs); ### Show line 71 cat(codedExample[71]); ### Also add code "foo" to utterances with code 'ipsum' moreCodedExample <- code_source(codedExample, c("[[ipsum]]" = "foo")); ### Show line 71 cat(moreCodedExample[71]); ### Use the 'indices' argument to add the code 'bar' to ### line 71 overCodedExample <- code_source(moreCodedExample, "bar", indices=71); cat(overCodedExample[71]);
Import a code book specification from a spreadsheet
codebook_fromSpreadsheet( x, localBackup = NULL, exportGoogleSheet = TRUE, xlsxPkg = c("rw_xl", "openxlsx", "XLConnect"), silent = rock::opts$get("silent") )codebook_fromSpreadsheet( x, localBackup = NULL, exportGoogleSheet = TRUE, xlsxPkg = c("rw_xl", "openxlsx", "XLConnect"), silent = rock::opts$get("silent") )
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. |
The code book specification as a rock code book object
### 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, ]; }### 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, ]; }
Use this function to export your codebook specification to a PDF file. To embed it in an R Markdown file, use !!! CREATE rock::knit_codebook() !!!
codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent") )codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent") )
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. |
x, invisibly
### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example (pre)registration specification data("exampleCodebook_1", package = "rock"); rock::codebook_to_pdf( exampleCodebook_1, file = tmpFile );### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example (pre)registration specification data("exampleCodebook_1", package = "rock"); rock::codebook_to_pdf( exampleCodebook_1, file = tmpFile );
This function replaces the column names in the mergedSourceDf data frame
in a rock_parsedSource or rock_parsedSources object with the full paths
to those code identifiers.
codeIds_to_codePaths( x, stripRootsFromCodePaths = rock::opts$get("stripRootsFromCodePaths") )codeIds_to_codePaths( x, stripRootsFromCodePaths = rock::opts$get("stripRootsFromCodePaths") )
x |
A |
stripRootsFromCodePaths |
Whether to strip the roots first (i.e. the type of code) |
An adapted rock_parsedSource or rock_parsedSources object.
This function names a vector with the leaf code
using the codeTreeMarker stored in the opts object as marker.
codePaths_to_namedVector(x)codePaths_to_namedVector(x)
x |
A vector of code paths. |
The named vector of code paths.
codePaths_to_namedVector( c("codes>reason>parent_feels", "codes>reason>child_feels") );codePaths_to_namedVector( c("codes>reason>parent_feels", "codes>reason>child_feels") );
Convenience function to get a list of all available coding schemes
codingSchemes_get_all()codingSchemes_get_all()
A list of all available coding schemes
rock::codingSchemes_get_all();rock::codingSchemes_get_all();
This function collapses all occurrences into groups
sharing the same identifier, by default the stanzaId
identifier ([[sid=..]]).
collapse_occurrences( parsedSource, collapseBy = "stanzaId", columns = NULL, logical = FALSE )collapse_occurrences( parsedSource, collapseBy = "stanzaId", columns = NULL, logical = FALSE )
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 ( |
A dataframe with one row for each value of of collapseBy and columns
for collapseBy and each of the columns, with in the cells the counts (if
logical is FALSE) or TRUE or FALSE (if logical is TRUE).
### Get path to example source exampleFile <- system.file("extdata", "example-1.rock", package="rock"); ### Parse example source parsedExample <- 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);### Get path to example source exampleFile <- system.file("extdata", "example-1.rock", package="rock"); ### Parse example source parsedExample <- 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);
Collect all coded utterances and optionally add some context (utterances before and utterances after) to create an overview of all coded fragments per code.
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") )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") )
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 (which
will be prepended with " |
context |
How many utterances before and after the target utterances to include in the fragments. If two values, the first is the number of utterances before, and the second, the number of utterances after the target utterances. |
includeDescendents |
Whether to also collect the fragments coded with descendent codes (i.e. child codes, 'grand child codes', etc; in other words, whether to collect the fragments recursively). |
attributes |
To only select coded utterances matching one or more values for one or more attributes, pass a list where every element's name is a valid (i.e. occurring) attribute name, and every element is a character value with a regular expression specifying all values for that attribute to select. |
heading |
Optionally, a title to include in the output. The title
will 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 utterances
when constructing the fragments (the raw versions contain all codes). Note that
this should be set to |
omitEmptyCodes |
Whether to still show the title for codes that do not occur or not. |
output |
Here, a path and filename can be provided where the result will be written. If provided, the result will be returned invisibly. |
outputViewer |
If showing output, where to show the output: in
the console ( |
template |
The template to load; either the name of one of the ROCK templates (currently, only 'default' is available), or the path and filename of a CSS file. |
rawResult |
Whether to return the raw result, a list of the fragments, 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 (replacing
double spaces with " |
codeHeadingFormatting, codeHeadingFormatting_html
|
A character value of the
form |
includeBootstrap |
Whether to include the default bootstrap CSS. |
preventOverwriting |
Whether to prevent overwriting of output files. |
silent |
Whether to provide ( |
By default, the output is optimized for inclusion in an R Markdown
document. To optimize output for the R console or a plain text
file, without any HTML codes, set add_html_tags to FALSE, and
potentially set cleanUtterances to only return the utterances,
without the codes.
Either a list of character vectors, or a single character value.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path( examplePath, "example-.rock" ); ### Parse single example source parsedExample <- rock::parse_source( exampleFile ); ### Show organised coded fragments in Markdown cat( 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 sources parsedExamples <- rock::parse_sources( examplePath, regex = "example-[1234].rock" ); cat( rock::collect_coded_fragments( parsedExamples, '[cC]ode2', context = 2 ) );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path( examplePath, "example-.rock" ); ### Parse single example source parsedExample <- rock::parse_source( exampleFile ); ### Show organised coded fragments in Markdown cat( 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 sources parsedExamples <- rock::parse_sources( examplePath, regex = "example-[1234].rock" ); cat( rock::collect_coded_fragments( parsedExamples, '[cC]ode2', context = 2 ) );
These functions can help when compressing vectors. They always compress
their input (x) into a single element by various means.
compress_with_sum(x) compress_with_or(x)compress_with_sum(x) compress_with_or(x)
x |
The vector to compress |
compress_with_sum computes the sum of the elements, doing its best to
convert all input values to numeric values.
compress_with_or returns 0 if all elements are FALSE, 0, NA or
empty character values (""), and 1 otherwise.
The compressed element
rock::compress_with_sum(c(1, '1', 0)); rock::compress_with_or(c(1, '1', 0)); rock::compress_with_or(c(0, '', 0, FALSE));rock::compress_with_sum(c(1, '1', 0)); rock::compress_with_or(c(1, '1', 0)); rock::compress_with_or(c(0, '', 0, FALSE));
This function simply computes confidence intervals for proportions.
confIntProp(x, n, conf.level = 0.95, plot = FALSE)confIntProp(x, n, conf.level = 0.95, plot = FALSE)
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. |
This function is the adapted source code of binom.test(). It
uses pbeta(), with some lines of code taken from the
binom.test() source. Specifically, the count for the low
category is specified as first 'shape argument' to pbeta(), and
the total count (either the sum of the count for the low category and the
count for the high category, or the total number of cases if
compareHiToLo is FALSE) minus the count for the low category
as the second 'shape argument'.
The confidence interval bounds in a twodimensional matrix, with the first column containing the lower bound and the second column containing the upper bound.
Unknown (see binom.test(); adapted by Gjalt-Jorn Peters)
Maintainer: Gjalt-Jorn Peters [email protected]
### Simple case rock::confIntProp(84, 200); ### Using vectors rock::confIntProp(c(2,3), c(10, 20), conf.level=c(.90, .95, .99));### Simple case rock::confIntProp(84, 200); ### Using vectors rock::confIntProp(c(2,3), c(10, 20), conf.level=c(.90, .95, .99));
These functions first import data from a 'data format', such as spreadsheets
in .xlsx format, comma-separated values files (.csv), or SPSS data
files (.sav). You can also just use R data frames (imported however you
want). These functions then use the columns you specified to convert these
data to one (oneFile=TRUE) or more (oneFile=FALSE) rock
source file(s), optionally including class instance
identifiers (such as case identifiers to identify participants, or location
identifiers, or moment identifiers, etc) and using those to link the
utterances to attributes from columns you specified. You can also precode
the utterances with codes you specify (if you ever would want to for some
reason).
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) )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) )
data |
The data frame containing the data to convert. |
output |
If |
omit_empty_rows |
Whether to omit rows where the values in the columns specified to convert to utterances are all empty (or contain only whitespace). |
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 instance
identifiers (e.g. case identifiers), as a named character vector, with
the values being the column names in the data frame, and the names being the
class 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 class
instance identifier to attach the attribute to. If only one column is passed
in |
utterance_classId |
When specifying multiple columns with utterances,
and |
utterance_comments |
A column with comments to be added to each utterance. |
commentPrefix |
If adding in comments, the prefix to use, typically
a number of hashes. Note that comment lines must start with a hash ( |
oneFile |
Whether to store everything in one source, or create one
source for each row of the data (if this is set to |
cols_to_sourceFilename |
The columns to use as unique part of the
filename of each source. These will be concatenated using
|
cols_in_sourceFilename_sep |
The separator to use when concatenating
the |
sourceFilename_prefix, sourceFilename_suffix
|
Strings that are
prepended and appended to the |
ciid_labels |
The labels for the class instance identifiers. Class instance identifiers have brief codes used in coding (e.g. 'cid' is the default for Case Identifiers, often used to identify participants) as well as more 'readable' labels that are used in the attributes (e.g. 'caseId' is the default class instance identifier for Case Identifiers). These can be specified here as a named vector, with each element being the label and the element's name the identifier. |
ciid_separator |
The separator for the class instance identifier - by
default, either an equals sign ( |
attributesFile |
Optionally, a file to write the attributes to if you don'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 utterances
using |
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 representing arguments to pass when importing the file. |
A source as a character vector.
### Get path to example files examplePath <- system.file("extdata", package="rock"); ### Get a path to file with example data frame exampleFile <- file.path(examplePath, "spreadsheet-import-test.csv"); ### Read data into a data frame dat <- read.csv(exampleFile); ### Convert data frame to a source source_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 result cat( source_from_df, sep = "\n" );### Get path to example files examplePath <- system.file("extdata", package="rock"); ### Get a path to file with example data frame exampleFile <- file.path(examplePath, "spreadsheet-import-test.csv"); ### Read data into a data frame dat <- read.csv(exampleFile); ### Convert data frame to a source source_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 result cat( source_from_df, sep = "\n" );
Tries to 'smartly' convert factor and character vectors to numeric.
convertToNumeric(vector, byFactorLabel = FALSE)convertToNumeric(vector, byFactorLabel = FALSE)
vector |
The vector to convert. |
byFactorLabel |
When converting factors, whether to do this
by their label value ( |
The converted vector.
rock::convertToNumeric(as.character(1:8));rock::convertToNumeric(as.character(1:8));
Count code occurrences
count_occurrences(x, codes = ".*", matchRegexAgainstPaths = TRUE)count_occurrences(x, codes = ".*", matchRegexAgainstPaths = TRUE)
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 |
A data.frame().
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-3.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code occurrences rock::count_occurrences( loadedExample );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-3.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code occurrences rock::count_occurrences( loadedExample );
This function can be used to specify a coding scheme that can then be used in analysis.
create_codingScheme( id, label, codes, codingInstructions = NULL, description = "", source = "" ) codingScheme_peterson codingScheme_levine codingScheme_williscreate_codingScheme( id, label, codes, codingInstructions = NULL, description = "", source = "" ) codingScheme_peterson codingScheme_levine codingScheme_willis
id |
An identifier for this coding scheme, consisting only of letters, 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 name is the corresponding code. |
description |
A description of this coding scheme (i.e. for information that does not fit in the label). |
source |
Optionally, a description, reference, or URL of a source for this coding scheme. |
An object of class rock_codingScheme of length 5.
An object of class rock_codingScheme of length 5.
An object of class rock_codingScheme of length 5.
A number of coding schemes for cognitive interviews are provided:
Coding scheme from Peterson, Peterson & Powell, 2017
Coding scheme from Levine, Fowler & Brown, 2005
Coding scheme from Willis, 1999
The coding scheme object.
This function creates a co-occurrence matrix based on one or more
coded sources. Optionally, it plots a heatmap, simply by calling
the stats::heatmap() function on that matrix.
create_cooccurrence_matrix( x, codes = x$convenience$codingLeaves, plotHeatmap = FALSE )create_cooccurrence_matrix( x, codes = x$convenience$codingLeaves, plotHeatmap = FALSE )
x |
The parsed source(s) as provided by |
codes |
The codes to include; by default, takes all codes. |
plotHeatmap |
Whether to plot the heatmap. |
The co-occurrence matrix; a matrix.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Create cooccurrence matrix rock::create_cooccurrence_matrix(parsedExamples);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Create cooccurrence matrix rock::create_cooccurrence_matrix(parsedExamples);
Create HTML fragment with CSS styling
css( template = "default", includeBootstrap = rock::opts$get("includeBootstrap") )css( template = "default", includeBootstrap = rock::opts$get("includeBootstrap") )
template |
The template to load; either the name of one of the ROCK templates (currently, only 'default' is available), or the path and filename of a CSS file. |
includeBootstrap |
Whether to include the default bootstrap CSS. |
A character vector with the HTML fragment.
This used to be a thin wrapper around textreadr::read_document() that also
writes the result to output, doing its best to correctly write UTF-8
(based on the approach recommended in this blog post). However,
textreadr was archived from CRAN. It now directly wraps the functions
that textreadr wraps: pdftools::pdf_text(), striprtf::read_rtf, and
it uses xml2 to import .docx and .odt files, and rvest to import
.html files, using the code from the textreadr package.
doc_to_txt( input, output = NULL, encoding = rock::opts$get("encoding"), newExt = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent") )doc_to_txt( input, output = NULL, encoding = rock::opts$get("encoding"), newExt = NULL, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent") )
input |
The path to the input file. |
output |
The path and filename to write to. If this is a path to
an 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. |
The converted source, as a character vector.
### This example requires the {xml2} package if (requireNamespace("xml2", quietly = TRUE)) { print( rock::doc_to_txt( input = system.file( "extdata/doc-to-test.docx", package="rock" ) ) ); }### This example requires the {xml2} package if (requireNamespace("xml2", quietly = TRUE)) { print( rock::doc_to_txt( input = system.file( "extdata/doc-to-test.docx", package="rock" ) ) ); }
This is a simple and relatively short codebook specification.
exampleCodebook_1exampleCodebook_1
An example of a codebook specification
Expand categorical attribute variables to a series of dichotomous variables
expand_attributes( data, attributes, valueLabels = NULL, prefix = "", glue = "__", suffix = "", falseValue = 0, trueValue = 1, valueFirst = TRUE, append = TRUE )expand_attributes( data, attributes, valueLabels = NULL, prefix = "", glue = "__", suffix = "", falseValue = 0, trueValue = 1, valueFirst = TRUE, append = TRUE )
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 created
variables than the values of the attributes. This can be set with the
|
prefix, suffix
|
The prefix and suffix to add to the variables names that are returned. |
glue |
The glue to paste the first part ad the second part of the composite 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 the attribute name, in the composite variable names. |
append |
Whether to append the columns to the supplied data frame or not. |
A data.frame
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Create a categorical attribute column parsedExample$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 columns parsedExample$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 result table(parsedExample$qdt$age_group, parsedExample$qdt$age_group__youngest); table(parsedExample$qdt$age_group, parsedExample$qdt$age_group__oldish);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Create a categorical attribute column parsedExample$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 columns parsedExample$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 result table(parsedExample$qdt$age_group, parsedExample$qdt$age_group__youngest); table(parsedExample$qdt$age_group, parsedExample$qdt$age_group__oldish);
These function can be used to convert one or more parsed sources to HTML, or to convert all sources to tabbed sections in Markdown.
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) )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) )
input |
An object of class |
output |
THe filename to write to. |
codeTree |
Codes from which code tree to export the codes. Valid options
are |
codingScheme |
With the ROCK, it's possible to use multiple coding scheme's
in parallel. The ROCK default is called |
regex |
An optional regular expression: only codes matching this regular expression will be selected. |
onlyChildrenOf |
A character vector of one or more regular expressions that
specify 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 have children) 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. |
A character vector.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Show results of exporting the codes rock::export_codes_to_txt(parsedExamples); ### Only show select a narrow set of codes rock::export_codes_to_txt( parsedExamples, leavesOnly=TRUE, includePath=FALSE, onlyChildrenOf = "inductFather", regex="3|5" );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Show results of exporting the codes rock::export_codes_to_txt(parsedExamples); ### Only show select a narrow set of codes rock::export_codes_to_txt( parsedExamples, leavesOnly=TRUE, includePath=FALSE, onlyChildrenOf = "inductFather", regex="3|5" );
Export the fully merged code tree(s)
export_fullyMergedCodeTrees(x, file)export_fullyMergedCodeTrees(x, file)
x |
A parsed source(s) object. |
file |
The file to save to. |
Invisibly, NULL.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); tempFile <- tempfile(fileext = ".svg"); ### Export merged code tree export_fullyMergedCodeTrees( loadedExample, tempFile );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); tempFile <- tempfile(fileext = ".svg"); ### Export merged code tree export_fullyMergedCodeTrees( loadedExample, tempFile );
Export a merged source data frame
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") )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") )
x |
The object with parsed sources. |
file |
The file to export to. |
exportArgs |
Optionally, arguments to pass to the function to use to export. |
preventOverwriting |
Whether to prevent overwriting if the file already exists. |
silent |
Whether to be silent or chatty. |
Silently, the object with parsed sources.
Export a ROCK project to a single ROCKproject file
export_ROCKproject( output, path = ".", config = NULL, includeRegex = NULL, excludeRegex = NULL, createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get("silent") )export_ROCKproject( output, path = ".", config = NULL, includeRegex = NULL, excludeRegex = NULL, createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get("silent") )
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 to
override. For supported options, see |
includeRegex |
A regular expression used to select files to include in the project file |
excludeRegex |
A regular expression used to omit files from the
project file; selection takes place after the selection by |
createDirs |
Whether to, if any directories in the |
preventOverwriting |
If the output file already exists, whether to
prevent it from being overwritten ( |
forceBaseZip |
Whether to force using the |
silent |
Whether to be chatty or silent |
Invisibly, output.
### Get path to example project examplePath <- system.file( "ROCKprojects", "exportable-ROCKproject-1", package="rock" ); ### Get a temporary filename to write to projectFilename <- tempfile( fileext = ".ROCKproject" ); ### Export it rock::export_ROCKproject( path = examplePath, output = projectFilename, silent = FALSE );### Get path to example project examplePath <- system.file( "ROCKprojects", "exportable-ROCKproject-1", package="rock" ); ### Get a temporary filename to write to projectFilename <- tempfile( fileext = ".ROCKproject" ); ### Export it rock::export_ROCKproject( path = examplePath, output = projectFilename, silent = FALSE );
These function can be used to convert one or more parsed sources to HTML, or to convert all sources to tabbed sections in Markdown.
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) )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) )
input |
An object of class |
output |
For |
template |
The template to load; either the name of one of the ROCK templates (currently, only 'default' is available), or the 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 |
A character vector or a list of character vectors.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Export results to a temporary directory tmpDir <- tempdir(check = TRUE); prettySources <- export_to_html(input = parsedExamples, output = tmpDir); ### Show first one print(prettySources[[1]]);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- rock::parse_sources( examplePath, regex = "(test|example)(.txt|.rock)" ); ### Export results to a temporary directory tmpDir <- tempdir(check = TRUE); prettySources <- export_to_html(input = parsedExamples, output = tmpDir); ### Show first one print(prettySources[[1]]);
This function exports data frames or matrices to HTML, sending output to one or more of the console, viewer, and one or more files.
exportToHTML( input, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS") )exportToHTML( input, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS") )
input |
Either a |
output |
The output: a character vector with one or more
of " |
tableOutputCSS |
The CSS to use for the HTML table. |
Invisibly, the (potentially concatenated) input as character
vector.
exportToHTML(mtcars[1:5, 1:5]);exportToHTML(mtcars[1:5, 1:5]);
Extract the codings by each coder using the coderId
extract_codings_by_coderId( input, recursive = TRUE, filenameRegex = ".*", postponeDeductiveTreeBuilding = TRUE, ignoreOddDelimiters = FALSE, encoding = rock::opts$get(encoding), silent = rock::opts$get(silent) )extract_codings_by_coderId( input, recursive = TRUE, filenameRegex = ".*", postponeDeductiveTreeBuilding = TRUE, ignoreOddDelimiters = FALSE, encoding = rock::opts$get(encoding), silent = rock::opts$get(silent) )
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 only store YAML fragments. |
ignoreOddDelimiters |
Whether to throw an error when encountering an odd number of YAML delimiters. |
encoding |
The encoding of the files to read. |
silent |
Whether to be chatty or silent. |
An object with the read sources.
Extract the UIDs (or SQUIDs) from a vector
extract_uids(x, returnSQUIDs = FALSE)extract_uids(x, returnSQUIDs = FALSE)
x |
The vector |
returnSQUIDs |
WHether to return the UIDs or the SQUIDs. |
A vector with (SQ)UIDs
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 );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 );
This function creates an R Markdown template from a {preregr} (pre)registrations form specification. Pass it the URL to a Google Sheet 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 a specification, or a loaded or imported {preregr} (pre)registration form.
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") )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") )
x |
The (pre)registration form (as produced by a call
to |
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 YAML front matter. |
yaml |
It is also possible to specify the YAML front matter directly
using 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 (the title of the (pre)registration form). |
showSpecification |
Whether to show the specification in the Rmd
output. When |
preventOverwriting |
Set to |
silent |
Whether to be silent or chatty. |
x, invisibly
newForm <- preregr::form_create( title = "Example form", version = "0.1.0" ); preregr::form_to_rmd_template( newForm );newForm <- preregr::form_create( title = "Example form", version = "0.1.0" ); preregr::form_to_rmd_template( newForm );
A TSSID is a Timestamped Source Identifier. It is a practically unique identifier for a source, conventionally the time and date the source was produced (e.g. when the data were collected, for example the time and date of an interview) in the UTC timezone and in ISO 8601 standard format.
generate_tssid(x = Sys.time(), addDelimiters = FALSE, designationSymbol = "=")generate_tssid(x = Sys.time(), addDelimiters = FALSE, designationSymbol = "=")
x |
The date and time to use. |
addDelimiters |
If |
designationSymbol |
The symbol to use to designate an instance
identifier for a class (can be " |
The tssid
rock::generate_tssid();rock::generate_tssid();
This function generates utterance identifiers. Utterance identifiers are
Short Quasi-Unique Identifiers (SQUIDs) generated using
the squids::squids() function.
generate_uids(x, origin = Sys.time(), follow = NULL, followBy = NULL)generate_uids(x, origin = Sys.time(), follow = NULL, followBy = NULL)
x |
The number of identifiers to generate. |
origin |
The origin to use when generating the actual
identifiers; see the |
follow |
A vector of one or more UIDs (or a list; lists are
recursively |
followBy |
When following a vector of UIDs, this can be used to specify the distance between the two vectors in centiseconds. |
A vector of UIDs.
### Produce and store five UIDs fiveUIDs <- rock::generate_uids(5); ### Look at them fiveUIDs; ### 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 UIDs rock::generate_uids( 5, follow = fiveUIDs ); ### Follow with a 'distance' of 5 utterances rock::generate_uids( 5, follow = fiveUIDs, followBy = 5 );### Produce and store five UIDs fiveUIDs <- rock::generate_uids(5); ### Look at them fiveUIDs; ### 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 UIDs rock::generate_uids( 5, follow = fiveUIDs ); ### Follow with a 'distance' of 5 utterances rock::generate_uids( 5, follow = fiveUIDs, followBy = 5 );
This function contains the general set of actions that are always used when recoding a source (e.g. check the input, document the justification, etc). Users should normally never call this function.
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"), ... )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"), ... )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
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 the
source(s) to process (see |
output |
If specified, the coded source will be written here. |
outputPrefix, outputSuffix
|
The prefix and suffix to add to the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
... |
Other arguments to pass to |
Invisibly, the recoded source(s) or source(s) object.
Get the code identifiers of all children, or all descendents (i.e. including grand-children, grand-grand-children, etc) of a code with a given identifier.
get_childCodeIds( x, parentCodeId, returnNodes = FALSE, includeParentCode = FALSE ) get_descendentCodeIds(x, parentCodeId, includeParentCode = FALSE)get_childCodeIds( x, parentCodeId, returnNodes = FALSE, includeParentCode = FALSE ) get_descendentCodeIds(x, parentCodeId, includeParentCode = FALSE)
x |
The parsed sources object |
parentCodeId |
The code identifier of the parent code |
returnNodes |
For |
includeParentCode |
Whether to include the parent code identifier in the result |
A character vector with code identifiers (or a list of nodes)
Get the code identifiers from QNA codings
get_codeIds_from_qna_codings( x, within = "network", return = "all", includeUIDs = TRUE )get_codeIds_from_qna_codings( x, within = "network", return = "all", includeUIDs = TRUE )
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 |
A character vector or data frame
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Read a souce coded with the Qualitative Network Approach qnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) ); rock::get_codeIds_from_qna_codings( qnaExample );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Read a souce coded with the Qualitative Network Approach qnaExample <- 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
get_dataframe_from_nested_list(x, nestingIn = "children")get_dataframe_from_nested_list(x, nestingIn = "children")
x |
The nested list |
nestingIn |
The name containing the nested lists |
A dataframe
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);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);
This function takes a character vector with regular expressions, a numeric vector with numeric indices, or a logical vector that is either as long as the source or has length 1; and then always returns a logical vector of the same length as the source.
get_source_filter( source, filter, ignore.case = TRUE, invert = FALSE, perl = TRUE, ... )get_source_filter( source, filter, ignore.case = TRUE, invert = FALSE, perl = TRUE, ... )
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 either as long as the source or has length 1. |
ignore.case |
Whether to apply the regular expression case sensitively
or not (see |
invert |
Whether to invert the result or not (i.e. whether the filter
specifies what you want to select ( |
perl |
Whether the regular expression (if |
... |
Any additional arguments are passed on to |
A logical vector of the same length as the source.
Get the state transition data frame
get_state_transition_df(x)get_state_transition_df(x)
x |
A state transition table as produced by a call
to |
A dataframe with columns fromState, toState,
and nrOfTransitions.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities exampleTable <- rock::get_state_transition_table( parsedExample ); exampleStateDf <- rock::get_state_transition_df( exampleTable );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities exampleTable <- rock::get_state_transition_table( parsedExample ); exampleStateDf <- rock::get_state_transition_df( exampleTable );
Get the Dot code for a state transition graph
get_state_transition_dot( x, labelFun = base::round, labelFunArgs = list(digits = 2) )get_state_transition_dot( x, labelFun = base::round, labelFunArgs = list(digits = 2) )
x |
A state transition table as produced by a call
to |
labelFun |
A function to apply to the edge labels in preprocessing. |
labelFunArgs |
Arguments to specify to |
The Dot code for a state transition graph.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities exampleTable <- rock::get_state_transition_table( parsedExample ); exampleStateDf <- rock::get_state_transition_df( exampleTable ); exampleDotCode <- rock::get_state_transition_dot( exampleStateDf ); DiagrammeR::grViz(exampleDotCode);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities exampleTable <- 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
get_state_transition_table(x, rawClassIdentifierCol = "state_raw")get_state_transition_table(x, rawClassIdentifierCol = "state_raw")
x |
A parsed source document as provided by |
rawClassIdentifierCol |
The identifier of the column in |
A table, with the 'from' states as rows and the 'to' states as columns
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities rock::get_state_transition_table( parsedExample );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show the state transition probabilities rock::get_state_transition_table( parsedExample );
This is a convenience function to use when displaying a source. It returns an object with the raw and clean utterances in a source, as well as the utterance identifiers and a list with vectors of the codes for each utterance.
get_utterances_and_codes_from_source(x, ...)get_utterances_and_codes_from_source(x, ...)
x |
Either the result of a call to |
... |
Arguments to |
A list containing $utterances_raw, $utterances_clean, $uids$,
$codeMatches, and $codesPerUtterance.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source res <- rock::get_utterances_and_codes_from_source( exampleFile );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source res <- rock::get_utterances_and_codes_from_source( exampleFile );
Return one or more values from a nested list in a list of vectors
get_vectors_from_nested_list(x, valuesIn = NULL, nestingIn = "children")get_vectors_from_nested_list(x, valuesIn = NULL, nestingIn = "children")
x |
The nested list |
valuesIn |
The names holding the values to return (in vectors) |
nestingIn |
The name containing the nested lists |
A list of vectors.
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") );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") );
This is just a convenience function to print a markdown or HTML heading at a given 'depth'.
heading( ..., headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = TRUE )heading( ..., headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = TRUE )
... |
The heading text: pasted together with no separator. |
headingLevel |
The level of the heading; the default can be set
with e.g. |
output |
Whether to output to HTML (" |
cat |
Whether to cat (print) the heading or just invisibly return it. |
The heading, invisibly.
heading("Hello ", "World", headingLevel=5); ### This produces: "\n\n##### Hello World\n\n"heading("Hello ", "World", headingLevel=5); ### This produces: "\n\n##### Hello World\n\n"
This is just a convenience function to convert a vector of strings into markdown or HTML headings at a given 'depth'.
heading_vector( x, headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = FALSE )heading_vector( x, headingLevel = rock::opts$get("defaultHeadingLevel"), output = "markdown", cat = FALSE )
x |
The vector. |
headingLevel |
The level of the heading; the default can be set
with e.g. |
output |
Whether to output to HTML (" |
cat |
Whether to cat (print) the heading or just invisibly return it. |
The heading, invisibly.
rock::heading_vector(c("Hello ", "World"), headingLevel=5); ### This produces: "\n\n##### Hello\n\n" and ### "\n\n##### World\n\n"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
heatmap_basic( data, x, y, fill, xLab = x, yLab = y, fillLab = fill, plotTitle = "Heatmap", fillScale = ggplot2::scale_fill_viridis_c(), theme = ggplot2::theme_minimal() )heatmap_basic( data, x, y, fill, xLab = x, yLab = y, fillLab = fill, plotTitle = "Heatmap", fillScale = ggplot2::scale_fill_viridis_c(), theme = ggplot2::theme_minimal() )
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. |
The heatmap, as a ggplot2 object.
rock::heatmap_basic(mtcars, 'am', 'cyl', 'mpg');rock::heatmap_basic(mtcars, 'am', 'cyl', 'mpg');
Import a ROCK project from a ROCKproject file
import_ROCKproject( input, path = ".", createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get(silent) )import_ROCKproject( input, path = ".", createDirs = FALSE, preventOverwriting = TRUE, forceBaseZip = FALSE, silent = rock::opts$get(silent) )
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 to
prevent them from being overwritten ( |
forceBaseZip |
Whether to force using the |
silent |
Whether to be chatty or silent |
Invisibly, output.
### Get path to example project exampleProjectFile <- system.file( "ROCKprojects", "example1.ROCKproject", package="rock" ); ### Get a temporary directory to write to temporaryDir <- tempdir(); ### Import the project rock::import_ROCKproject( input = exampleProjectFile, path = temporaryDir, silent = FALSE );### Get path to example project exampleProjectFile <- system.file( "ROCKprojects", "example1.ROCKproject", package="rock" ); ### Get a temporary directory to write to temporaryDir <- tempdir(); ### Import the project rock::import_ROCKproject( input = exampleProjectFile, path = temporaryDir, silent = FALSE );
Import a source from Google Documents
import_source_from_gDocs(x, localFile = NULL)import_source_from_gDocs(x, localFile = NULL)
x |
The URL to the source: has to be viewable publicly! |
localFile |
A local file (where to store a local backup). |
The source contents.
### 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; }### 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; }
This function combines successive calls to parse_sources(),
collect_coded_fragments() and show_inductive_code_tree().
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() )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() )
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 pass
to |
deductive_tree_args |
Not yet implemented. |
The parsedSources object.
### Get path to example source examplePath <- 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)") );### Get path to example source examplePath <- 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)") );
These functions load one or more source(s) from a file or
a string and store it in memory for further processing.
Note that you'll probably want to clean the sources
first, using one of the clean_sources() functions,
and you'll probably want to add utterance identifiers
to each utterance using one of the prepending_uids()
functions.
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") )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") )
input |
The filename or contents of the source
for |
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; only files matching this regular expression are processed. |
ignoreRegex |
Regular expression indicating which files to ignore. This is a perl-style regular expression (see base::regex). |
recursive |
Whether to search all subdirectories ( |
full.names |
Whether to store source names as filenames only or whether to include paths. |
Invisibly, an R character vector of
classes rock_source and character.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedSource <- rock::load_source(exampleFile);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedSource <- rock::load_source(exampleFile);
This function creates a ROCK project configuration file in the YAML format. See the Details section for more information.
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 )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 )
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 the project's configuration file. One never knows whether being able to do that comes in handy at some point. |
path |
If not |
For more information about the ROCK project configuration file format,
see the ROCKproject-format vignette. You can view this from R using:
vignette("ROCKproject-format", package="rock");
You can also visit it at https://rock.opens.science/articles/ROCKproject-format.html.
A list with the passed configuration in a list called
$input, and as YAML in a character vector called $yaml.
### To get the default configuration, ### just pass no arguments: defaultConfig <- rock::make_ROCKproject_config(); ### You can then extract the object with settings config <- defaultConfig$input; ### Edit some of them config$project$title <- "Some new title"; ### Call the function again with the new arguments myConfig <- rock::make_ROCKproject_config( project = config$project, codebook = config$codebook, sources = config$sources, workflow = config$workflow, extra = config$extra ); ### View the result cat(myConfig$yaml);### To get the default configuration, ### just pass no arguments: defaultConfig <- rock::make_ROCKproject_config(); ### You can then extract the object with settings config <- defaultConfig$input; ### Edit some of them config$project$title <- "Some new title"; ### Call the function again with the new arguments myConfig <- rock::make_ROCKproject_config( project = config$project, codebook = config$codebook, sources = config$sources, workflow = config$workflow, extra = config$extra ); ### View the result cat(myConfig$yaml);
These functions can be used to mask a set of utterances or one or more sources.
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 )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 )
input |
For |
output |
For |
proportionToMask |
The proportion of utterances to mask, from 0 (none) to 1 (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 to mask (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 the filenames when writing the processed files to disk. |
recursive |
Whether to search all subdirectories ( |
filenameRegex |
A regular expression to match against located files; only files matching this regular expression are processed. |
filenameReplacement |
A character vector with two elements that represent,
respectively, the |
A character vector for mask_utterance and mask_source, or a list of
character vectors, for mask_sources.
### Mask text but not the codes rock::mask_utterances( paste0( "Lorem ipsum dolor sit amet, consectetur adipiscing ", "elit. [[expAttitude_expectation_73dnt5z1>earplugsFeelUnpleasant]]" ) )### Mask text but not the codes rock::mask_utterances( paste0( "Lorem ipsum dolor sit amet, consectetur adipiscing ", "elit. [[expAttitude_expectation_73dnt5z1>earplugsFeelUnpleasant]]" ) )
This is just a convenience function that takes a vector of deliminaters and returns a list of delimiter pairs.
match_consecutive_delimiters( x, errorOnInvalidX = FALSE, errorOnOdd = FALSE, onOddIgnoreFirst = FALSE )match_consecutive_delimiters( x, errorOnInvalidX = FALSE, errorOnOdd = FALSE, onOddIgnoreFirst = FALSE )
x |
The vector with delimiter indices |
errorOnInvalidX |
Whether to return |
errorOnOdd |
Whether to throw an error if the number of delimiter indices is odd. |
onOddIgnoreFirst |
If the number of delimiter indices is odd and no
error is thrown, whether to ignore the first ( |
A list where each element is a two-element vector with the two consecutive delimiters
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 ) );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 ) );
This function takes sets of sources and merges them using the utterance identifiers (UIDs) to match them.
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 )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 )
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 exception
is if " |
outputPrefix, outputSuffix
|
A pre- and/or suffix to add to the filename when writing the merged sources (especially useful when writing them to the same directory). |
primarySourcesRegex |
A regular expression that specifies how to recognize the primary sources (i.e. the files used as the basis, to which the codes from other sources are added). |
primarySourcesIgnoreRegex |
A regular expression that specifies which files to ignore as primary files. |
primarySourcesPath |
The path containing the primary sources. |
recursive, primarySourcesRecursive
|
Whether to read files from
sub-directories ( |
filenameRegex |
Only files matching this regular expression are read. |
primarySourcesFileList, sourcesFileList
|
Alternatively to using regular
expressions, lists of full paths and filenames to the primary sources and all
sources to process can be specified using these arguments. If this is used,
neither can be |
postponeDeductiveTreeBuilding |
Whether to imediately try to build the deductive
tree(s) based on the information in this file ( |
ignoreOddDelimiters |
If an odd number of YAML delimiters is encountered, whether this
should 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 called
by |
Invisibly, a list of the parsed, primary, and merged sources.
Convert a number to a date using Excel's system
number_as_xl_date(x)number_as_xl_date(x)
x |
The number(s) |
The date(s)
preregr::number_as_xl_date(44113);preregr::number_as_xl_date(44113);
The rock::opts object contains three functions to set, get, and reset
options used by the rock package. Use rock::opts$set to set options,
rock::opts$get to get options, or rock::opts$reset to reset specific or
all options to their default values.
optsopts
An object of class list of length 4.
It is normally not necessary to get or set rock options. The defaults implement
the Reproducible Open Coding Kit (ROCK) standard, and deviating from these defaults
therefore means the processed sources and codes are not compatible and cannot be
processed by other software that implements the ROCK. Still, in some cases this
degree of customization might be desirable.
The following arguments can be passed:
For rock::opts$set, the dots can be used to specify the options
to set, in the format option = value, for example, utteranceMarker = "\n". For
rock::opts$reset, a list of options to be reset can be passed.
For rock::opts$set, the name of the option to set.
For rock::opts$get, the default value to return if the
option has not been manually specified.
Some of the options that can be set (see rock::opts$defaults for the
full list):
A named character vector with one or more regular expressions that specify how to extract the codes (that were used to code the sources). These regular expressions must each contain one capturing group to capture the codes.
A named character vector with one or more regular expressions that specify how to extract the different types of identifiers. These regular expressions must each contain one capturing group to capture the identifiers.
A named character vector with one or more regular expressions that specify how to extract the different types of sections.
The names of the idRegexes that, if missing, should receive
autogenerated identifiers (which consist of 'autogenerated_' followed by an
incrementing number).
This regular expression is matched with all codes after they have been
extracted using the codeRegexes regular expression (i.e. they're matched against the
codes themselves without, for example, the square brackets in the default code regex). Any
codes matching this noCodes regular expression will be ignored, i.e., removed from the
list of codes.
For inductive coding, this marker is used to indicate
hierarchical relationships between codes. The code at the left hand side of this marker will
be considered the parent code of the code on the right hand side. More than two levels
can be specified in one code (for example, if the inductiveCodingHierarchyMarker is '>',
the code grandparent>child>grandchild would indicate codes at three levels.
The name of YAML fragments containing case attributes (e.g. metadata, demographic variables, quantitative data about cases, etc).
The name of YAML fragments containing (parts of) deductive coding trees.
The regular expression that is used to extract the YAML fragments.
A character vector of two elements specifying the opening and closing delimiters of codes (conform the default ROCK convention, two square brackets). The square brackets will be escaped; other characters will not, but will be used as-is.
The regular expression that is used to delete lines before any other processing. This can be used to enable adding comments to sources, which are then ignored during analysis.
Whether to include the default bootstrap CSS.
How to specify breaks between utterances in the source(s). The
ROCK convention is to use a newline (\\n).
A regular expression specifying the coder identifier, specified similarly to the codeRegexes.
The identifier to use for utterances that do not have a coder id (i.e. utterance that occur in a source that does not specify a coder id, or above the line where a coder id is specified).
### Get the default utteranceMarker rock::opts$get(utteranceMarker); ### Set it to a custom version, so that every line starts with a pipe rock::opts$set(utteranceMarker = "\n|"); ### Check that it worked rock::opts$get(utteranceMarker); ### Reset this option to its default value rock::opts$reset(utteranceMarker); ### Check that the reset worked, too rock::opts$get(utteranceMarker);### Get the default utteranceMarker rock::opts$get(utteranceMarker); ### Set it to a custom version, so that every line starts with a pipe rock::opts$set(utteranceMarker = "\n|"); ### Check that it worked rock::opts$get(utteranceMarker); ### Reset this option to its default value rock::opts$reset(utteranceMarker); ### Check that the reset worked, too rock::opts$get(utteranceMarker);
Padd a character vector
padString(x, width, padding = " ")padString(x, width, padding = " ")
x |
The character vector |
width |
The width to pad to |
padding |
The character to pad with |
x with padding appended to each element
padString( c("One", "Two", "Three" ), width = 7 );padString( c("One", "Two", "Three" ), width = 7 );
These function parse one (parse_source) or more (parse_sources) sources and the
contained identifiers, sections, and codes.
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, ...)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, ...)
text, file
|
As |
utteranceLabelRegexes |
Optionally, a list with two-element vectors to preprocess utterances before they are stored as labels (these 'utterance perl regular expression! |
ignoreOddDelimiters |
If an odd number of YAML delimiters is encountered, whether this
should result in an error ( |
checkClassInstanceIds |
Whether to check for the occurrence of class instance identifiers specified in the attributes. |
postponeDeductiveTreeBuilding |
Whether to imediately try to build the deductive
tree(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 attributes into the qualitative data table (i.e., the data frame with the data fragments and codes). |
removeSectionBreakRows, removeIdentifierRows, removeEmptyRows
|
Whether to remove from the QDT, respectively: rows containing section breaks; rows containing only (class instance) identifiers; and empty rows. |
suppressDuplicateInstanceWarnings |
Whether to suppress warnings about duplicate instances (as resulting from inconsistent specifications of attributes 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 will
be ignored. Multiple extensions can be separated by a pipe ( |
regex |
Instead of specifing an extension, it's also possible to specify a regular
expression; only files matching this regular expression are read. If specified, |
recursive |
Whether to also process subdirectories ( |
mergeInductiveTrees |
Merge multiple inductive code trees into one; this functionality is currently not yet implemented. |
For rock::parse_source(), an object of class rock_parsedSource;
for rock::parse_sources(), an object of class rock_parsedSources. These
objects contain the original source(s) as well as the final data frame with
utterances and codes, as well as the code structures.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- 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 directory parsedExamples <- 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 Approach qnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- 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 directory parsedExamples <- 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 Approach qnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) );
Parsing sources separately for each coder
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) )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) )
input |
For |
ignoreOddDelimiters |
If an odd number of YAML delimiters is encountered, whether this
should result in an error ( |
postponeDeductiveTreeBuilding |
Whether to imediately try to build the deductive
tree(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; only files matching this regular expression are processed. |
For rock::parse_source_by_coderId(), an object of
class rock_parsedSource; for rock::parse_sources_by_coderId(), an
object of class rock_parsedSources. These objects contain the original
source(s) as well as the final data frame with utterances and codes, as
well as the code structures.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source_by_coderId(exampleFile);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source_by_coderId(exampleFile);
Create an ENA network out of one or more parsed sources
parsed_sources_to_ena_network( x, unitCols, conversationCols = "originalSource", codes = x$convenience$codingLeaves, metadata = x$convenience$attributesVars )parsed_sources_to_ena_network( x, unitCols, conversationCols = "originalSource", codes = x$convenience$codingLeaves, metadata = x$convenience$attributesVars )
x |
The parsed source(s) as provided by |
unitCols |
The columns that together define units (e.g. utterances in each source that belong together, for example because they're about the same topic). |
conversationCols |
The columns that together define conversations (e.g. separate sources, 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 the metadata. By default, takes all read metadata. |
The result of a call to rENA::ena.plot.network(), if that is
installed.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- 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's nChunks <- nrow(parsedExamples$mergedSourceDf) %/% 10; parsedExamples$mergedSourceDf$units <- c(rep(1:nChunks, each=10), rep(max(nChunks), nrow(parsedExamples$mergedSourceDf) - (10*nChunks))); ### Generate ENA plot enaPlot <- rock::parsed_sources_to_ena_network(parsedExamples, unitCols='units'); ### Show the resulting plot print(enaPlot);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Parse a selection of example sources in that directory parsedExamples <- 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's nChunks <- nrow(parsedExamples$mergedSourceDf) %/% 10; parsedExamples$mergedSourceDf$units <- c(rep(1:nChunks, each=10), rep(max(nChunks), nrow(parsedExamples$mergedSourceDf) - (10*nChunks))); ### Generate ENA plot enaPlot <- rock::parsed_sources_to_ena_network(parsedExamples, unitCols='units'); ### Show the resulting plot print(enaPlot);
These functions add lines with class instance identifiers to the beginning
of one or more sources that were read with one of the
loading_sources functions.
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") )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") )
input |
The source, or list of sources, as
produced by one of the |
ciids |
A named character vector, where each element's name is the class identifier (e.g. "codeId" or "participantId") and each element is the class instance identifier. |
output |
If specified, the coded source will be written here. |
allOnOneLine |
Whether to add all class instance identifiers to one
line ( |
designationSymbol |
The symbol to use to designate an instance
identifier 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/or append to the filenames to distinguish them from the input filenames. |
recursive |
Whether to also read files from all subdirectories
of the |
filenameRegex |
Only input files matching this patterns will be read. |
Invisibly, the coded source object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Add a coder identifier loadedExample <- rock::prepend_ciids_to_source( loadedExample, c("codeId" = "iz0dn96") ); ### Show lines 1-5 cat(loadedExample[1:5]);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Add a coder identifier loadedExample <- rock::prepend_ciids_to_source( loadedExample, c("codeId" = "iz0dn96") ); ### Show lines 1-5 cat(loadedExample[1:5]);
This function prepends unique utterance identifiers to each
utterance (line) in a source. Note that you'll probably want
to clean the sources using clean_sources() first.
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) )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) )
input |
The filename or contents of the source
for |
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 are
recursively |
followBy |
When following a vector of UIDs, this can be used to
specify 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 the filenames when writing the processed files to disk. |
uidSpacing |
The number of UID spaces to leave between sources (in case more data may follow in with source). |
The source with prepended uids, either invisible (if output
if specified) or visibly (if not).
### Simple example rock::prepend_ids_to_source( "brief\nexample\nsource" ); ### Example including fake YAML fragments longerExampleText <- 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 );### Simple example rock::prepend_ids_to_source( "brief\nexample\nsource" ); ### Example including fake YAML fragments longerExampleText <- 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 );
This function adds a line with a TSSID (a time-stamped source identifier)
to the beginning of a source that was read with one of
the loading_sources functions. When combined with UIDs, TSSIDs are
virtually unique references to a specific data fragment.
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") )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") )
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 instance
identifier 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. |
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), a T, four
digits (two for the hour and two for the minute), and a Z (to designate
that the time is specified in the UTC timezone). TSSIDs are valid ISO8601
standard date/times.
Invisibly, the coded source object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Add a coder identifier loadedExample <- rock::prepend_tssid_to_source( loadedExample, moment = "2025-05-28 11:30 CEST" ); ### Show the first line cat(loadedExample[1]);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Parse single example source loadedExample <- rock::load_source(exampleFile); ### Add a coder identifier loadedExample <- rock::prepend_tssid_to_source( loadedExample, moment = "2025-05-28 11:30 CEST" ); ### Show the first line cat(loadedExample[1]);
Efficiently preprocess data
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") )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") )
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. |
The preprocessed source as character vector.
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 text cat(exampleText); ### Show preprocessed example text rock::preprocess_source( exampleText );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 text cat(exampleText); ### Show preprocessed example text rock::preprocess_source( exampleText );
To initialize a (pre)registration, pass the URL to a Google Sheet 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 a specification, or a loaded or imported {preregr} (pre)registration form.
prereg_initialize(x, initialText = "Unspecified")prereg_initialize(x, initialText = "Unspecified")
x |
The (pre)registration form specification, as a URL to a Google Sheet or online file or as the path to a locally stored file. |
initialText |
The text to initialize every field with. |
For an introduction to working with {preregr} (pre)registrations, see the "Specifying preregistration content" vignette.
The empty (pre)registration specification.
rock::prereg_initialize( "preregQE_v0_95" );rock::prereg_initialize( "preregQE_v0_95" );
This function adds HTML tags to a source to allow pretty printing/viewing. For an example, visit https://rock.opens.science/articles/rock.html.
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) )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) )
x |
The source, as imported with |
heading |
Optionally, a title to include in the output. The title
will 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 the result will be written. If provided, the result will be returned invisibly. |
outputViewer |
If showing output, where to show the output: in
the console ( |
template |
The template to load; either the name of one of the ROCK templates (currently, only 'default' is available), or the 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 second
space with |
includeBootstrap |
Whether to include the default bootstrap CSS. |
preventOverwriting |
Whether to prevent overwriting of output files. |
silent |
Whether to provide ( |
A character vector with the prettified source
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- 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.html rock::prettify_source( exampleFile );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- 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.html rock::prettify_source( exampleFile );
Plot the graphs in a list of graphs
## S3 method for class 'rock_graphList' print(x, ...)## S3 method for class 'rock_graphList' print(x, ...)
x |
The list of graphs |
... |
Any other arguments are passed to |
x, invisibly
The Linear Topic Map format, LTM (https://ontopia.net/download/ltm.html), allows specification of networks in a human-readable format.
qna_to_tlm( x, topicmapId = "rock_qna_topicmap", topicmapTitle = "A ROCK QNA Topic Map" )qna_to_tlm( x, topicmapId = "rock_qna_topicmap", topicmapTitle = "A ROCK QNA Topic Map" )
x |
The parsed source object (as produced by |
topicmapId, topicmapTitle
|
The topic map's identifier and title. |
If x is a single parsed source: a character vector holding the
Linear Topic Map specification; or, if multiple network coding schemes were
used in parallel, each in a list. If x contains multiple parseds sources,
a list of such objects (i.e., a list of vectors, or a list of lists of
vectors).
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Read a souce coded with the Qualitative Network Approach qnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) ); ### Convert and show the topic map cat( rock::qna_to_tlm( qnaExample ), sep="\n" );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Read a souce coded with the Qualitative Network Approach qnaExample <- rock::parse_source( file.path( examplePath, "network-example-1.rock" ) ); ### Convert and show the topic map cat( rock::qna_to_tlm( qnaExample ), sep="\n" );
Qualitative/Unified Exploration of State Transitions
quest( x, rawClassIdentifierCol = "state_raw", labelFun = base::round, labelFunArgs = list(digits = 2) )quest( x, rawClassIdentifierCol = "state_raw", labelFun = base::round, labelFunArgs = list(digits = 2) )
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 |
A DiagrammeR::grViz() object, which will print to show the
QUEST graph.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show a QUEST graph rock::quest( parsedExample );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "state-example-1.rock"); ### Parse single example source parsedExample <- rock::parse_source(exampleFile); ### Show a QUEST graph rock::quest( parsedExample );
Bind lots of dataframes together rowwise
rbind_df_list(x)rbind_df_list(x)
x |
A list of dataframes |
A dataframe
rbind_df_list(list(Orange, mtcars, ChickWeight));rbind_df_list(list(Orange, mtcars, ChickWeight));
Simple alternative for rbind.fill or bind_rows
rbind_dfs(x, y, clearRowNames = TRUE)rbind_dfs(x, y, clearRowNames = TRUE)
x |
One dataframe |
y |
Another dataframe |
clearRowNames |
Whether to clear row names (to avoid duplication) |
The merged dataframe
rbind_dfs(Orange, mtcars);rbind_dfs(Orange, mtcars);
Currently reads spreadsheets from Google Sheets or from xlsx, csv,
or sav files.
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") )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") )
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 to check for presence. A named list of vectors. |
localBackup |
If not |
exportGoogleSheet |
If |
flattenSingleDf |
Whether to return the result as a data frame if only 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. |
A list of dataframes, or, if only one data frame was loaded and
flattenSingleDf is TRUE, a data frame.
### 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, ]; }### 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, ]; }
This function conditionally adds new child codes under a code. Where
recode_split() removes the original code (splitting
it into the new codes), this function retains the original, adding the new
codes as sub-codes.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
codes |
A single character value with the code to add the child codes to. |
childCodes |
A named list with specifying when to add which
child code. Each element of this list is a filtering criterion that will be
passed on to |
filter |
Optionally, a filter to apply to specify a subset of the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the changed source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExampleSource <- 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 );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExampleSource <- 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 );
These functions remove one or more codes from a source, and make it easy to justify that decision.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
codes |
A character vector with codes to remove. |
filter |
Optionally, a filter to apply to specify a subset of the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the recoded source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Delete two codes, moving children to the codes' parents recoded_source <- rock::recode_delete( loadedExample, codes=c("childCode2", "childCode1"), silent=FALSE ); ### Process an entire directory list_of_recoded_sources <- rock::recode_delete( examplePath, codes=c("childCode2", "childCode1"), silent=FALSE );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Delete two codes, moving children to the codes' parents recoded_source <- rock::recode_delete( loadedExample, codes=c("childCode2", "childCode1"), silent=FALSE ); ### Process an entire directory list_of_recoded_sources <- rock::recode_delete( examplePath, codes=c("childCode2", "childCode1"), silent=FALSE );
This function merges two or more codes into one.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
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 the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the changed source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_merge( loadedExample, codes=c("childCode2", "grandchildCode2"), mergeToCode="mergedCode", silent=FALSE );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_merge( loadedExample, codes=c("childCode2", "grandchildCode2"), mergeToCode="mergedCode", silent=FALSE );
These functions move a code to a different parent (and therefore, ancestry) in one or more sources.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
codes |
A character vector with codes to move. |
newAncestry |
The new parent code, optionally including the partial or 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 the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the changed source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_move( loadedExample, codes=c("childCode2", "childCode1"), newAncestry = "parentCode2", silent=FALSE );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_move( loadedExample, codes=c("childCode2", "childCode1"), newAncestry = "parentCode2", silent=FALSE );
These functions rename one or more codes in one or more sources.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
codes |
A named character vector with codes to rename. Each element
should be the new code, and the element's name should be the old code (so
e.g. |
filter |
Optionally, a filter to apply to specify a subset of the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the changed source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_rename( loadedExample, codes=c(childCode2 = "grownUpCode2", grandchildCode2 = "almostChildCode2"), silent=FALSE );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Move two codes to a new parent, showing progress recoded_source <- rock::recode_rename( loadedExample, codes=c(childCode2 = "grownUpCode2", grandchildCode2 = "almostChildCode2"), silent=FALSE );
This function conditionally splits a code into multiple codes. Note that you
may want to use recode_addChildCodes() instead to not lose the
original coding.
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") )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") )
input |
One of 1) a character string specifying the path to a file
with a source; 2) an object with a loaded source as produced by a call
to |
codes |
A single character value with the code to split. |
splitToCodes |
A named list with specifying when to split to which
new code. Each element of this list is a filtering criterion that will be
passed on to |
filter |
Optionally, a filter to apply to specify a subset of the
source(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 the filenames when writing the processed files to disk, in case multiple sources 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 to
this file. If not, it is saved to the |
preventOverwriting |
Whether to prevent overwriting existing files
when writing the files to |
encoding |
The encoding to use. |
silent |
Whether to be chatty or quiet. |
Invisibly, the changed source(s) or source(s) object.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Split a code into two codes, showing progress recoded_source <- rock::recode_split( loadedExample, codes="childCode1", splitToCodes = list( and_REPLACED = " and ", book_REPLACED = "book", else_REPLACED = TRUE ), silent=FALSE );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::load_source(exampleFile); ### Split a code into two codes, showing progress recoded_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
repeatStr(n = 1, str = " ")repeatStr(n = 1, str = " ")
n, str
|
Normally, respectively the frequency with which to repeat the string and the string to repeat; but the order of the inputs can be switched as well. |
A character vector of length 1.
### 10 spaces: repStr(10); ### Three euro symbols: repStr("\u20ac", 3);### 10 spaces: repStr(10); ### Three euro symbols: repStr("\u20ac", 3);
Show all coded fragments
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) )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) )
x |
The parsed source(s) as provided by |
root |
The root code |
context |
How many utterances before and after the target utterances to include in the fragments. If two values, the first is the number of utterances before, and the second, the number of utterances after the target utterances. |
heading |
Optionally, a title to include in the output. The title
will 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 utterances
when constructing the fragments (the raw versions contain all codes). Note that
this should be set to |
output |
Here, a path and filename can be provided where the result will be written. If provided, the result will be returned invisibly. |
outputViewer |
If showing output, where to show the output: in
the console ( |
template |
The template to load; either the name of one of the ROCK templates (currently, only 'default' is available), or the 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 ( |
Invisibly, the coded fragments in a character vector.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path( examplePath, "example-1.rock" ); ### Parse single example source parsedExample <- rock::parse_source( exampleFile ); ### Show organised coded fragments in Markdown cat( rock::resultsOverview_allCodedFragments( parsedExample ) );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path( examplePath, "example-1.rock" ); ### Parse single example source parsedExample <- rock::parse_source( exampleFile ); ### Show organised coded fragments in Markdown cat( rock::resultsOverview_allCodedFragments( parsedExample ) );
This package implements an open standard for working with qualitative data, as such, it has two parts: a file format/convention and this R package that facilitates working with .rock files.
The .rock files are plain text files where a number of conventions are used
to 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
rock R Package FunctionsThe most important functions are parse_source() to parse one source and parse_sources()
to parse multiple sources simultaneously. clean_source() and clean_sources() can be used
to clean sources, and prepend_ids_to_source() and prepend_ids_to_sources() can be
used to quickly generate UIDs and prepend them to each utterance in a source.
For analysis, create_cooccurrence_matrix(), collapse_occurrences(), and
collect_coded_fragments() can be used.
Maintainer: Gjalt-Jorn Peters [email protected] (ORCID) [copyright holder]
Authors:
Szilvia Zörgő (ORCID)
Useful links:
Get the roots from a vector with code paths
root_from_codePaths(x)root_from_codePaths(x)
x |
A vector of code paths. |
A vector with the root of each element.
root_from_codePaths( c("codes>reason>parent_feels", "codes>reason>child_feels") );root_from_codePaths( c("codes>reason>parent_feels", "codes>reason>child_feels") );
This function creates a plain text file, a .rock source, that can be
coded when conducting Response Process Evaluation.
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") )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") )
data |
A (wide) data frame containing at least the participants' answers to the items and to the meta questions (but optionally, the iteration, batch, and population). |
iterationId, batchId, populationId
|
If the iteration, batch, and
population identifiers are contained in the data frame passed as |
itemVarNames |
The variable names with the participants' responses
to the items, in a named character vector, with each element's name being
the 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 meta question, and each list element (i.e. the name of each character vector) specifying the item identifier that the meta questions in the corresponding character vector belong to. |
metaquestionVarNames |
The variable names with the participants'
responses to the meta questions, in a named character vector, with each
element's name being the meta question's identifier, and each element
the variable name in |
itemContents |
A named character vector with each item's content, with the values being the content and the names the item identifiers. |
metaquestionContents |
A named character vector with each meta question's content, with the values being the content and the names the meta 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 ( |
The created source, as a character vector (invisibly);
When conducting analyses, you make many choices that ideally, you document and justify. This function saves stored justifications to a file.
save_workspace( file = rock::opts$get("justificationFile"), encoding = rock::opts$get("encoding"), append = FALSE, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent") )save_workspace( file = rock::opts$get("justificationFile"), encoding = rock::opts$get("encoding"), append = FALSE, preventOverwriting = rock::opts$get("preventOverwriting"), silent = rock::opts$get("silent") )
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. |
The result of a call to justifier::export_justification().
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- 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 file temporaryFilename <- tempfile(); rock::save_workspace(file = temporaryFilename);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- 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 file temporaryFilename <- tempfile(); rock::save_workspace(file = temporaryFilename);
Show a table with all attributes in the RStudio viewer and/or console
show_attribute_table( x, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS") )show_attribute_table( x, output = rock::opts$get("tableOutput"), tableOutputCSS = rock::opts$get("tableOutputCSS") )
x |
A |
output |
The output: a character vector with one or more
of " |
tableOutputCSS |
The CSS to use for the HTML table. |
x, invisibly, unless being knitted into R Markdown,
in which case a knitr::asis_output()-wrapped character vector is returned.
Show the fully merged code tree(s)
show_fullyMergedCodeTrees(x)show_fullyMergedCodeTrees(x)
x |
A parsed source(s) object. |
The result of a call to DiagrammeR::render_graph().
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show merged code tree show_fullyMergedCodeTrees(loadedExample);### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show merged code tree show_fullyMergedCodeTrees(loadedExample);
This function shows one or more inductive code trees.
show_inductive_code_tree( x, codes = ".*", output = "both", headingLevel = 3, nodeStyle = list(shape = "box", fontname = "Arial"), edgeStyle = list(arrowhead = "none"), graphStyle = list(rankdir = "LR") )show_inductive_code_tree( x, codes = ".*", output = "both", headingLevel = 3, nodeStyle = list(shape = "box", fontname = "Arial"), edgeStyle = list(arrowhead = "none"), graphStyle = list(rankdir = "LR") )
x |
A |
codes |
A regular expression: only code trees from codes coded with 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 the code tree as text. |
nodeStyle, edgeStyle, graphStyle
|
Arguments to pass on to,
respectively, |
x, invisibly, unless being knitted into R Markdown,
in which case a knitr::asis_output()-wrapped character vector is returned.
Soft Non-numeric Occurrence Estimation (SNOE) plot
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") )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") )
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 and greyscale versions of the SNOE plot. |
silent |
Whether to be chatty or silent |
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-3.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code occurrence estimates rock::snoe_plot( loadedExample ); ### Load two example sources loadedExamples <- rock::parse_sources( examplePath, regex = "example-[34].rock" ); rock::snoe_plot( loadedExamples );### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-3.rock"); ### Load example source loadedExample <- rock::parse_source(exampleFile); ### Show code occurrence estimates rock::snoe_plot( loadedExample ); ### Load two example sources loadedExamples <- rock::parse_sources( examplePath, regex = "example-[34].rock" ); rock::snoe_plot( loadedExamples );
This function splits long lines at a given number of characters,
keeping words intact. It's basically a wrapper around strwrap().
split_long_lines( x, length = 60, collapseResult = FALSE, splitString = rock::opts$get("utteranceMarker") )split_long_lines( x, length = 60, collapseResult = FALSE, splitString = rock::opts$get("utteranceMarker") )
x |
The string (e.g. a source) |
length |
The maximum length |
collapseResult |
Whether to collapse the result from a vector (with
line breaks separating the elements) to a single character value (where
the vector elements are glued together using |
splitString |
The character to use to split lines. |
A character vector.
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." ) ) );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." ) ) );
This function strips the root (just the first element) from a code path,
using the codeTreeMarker stored in the opts object as marker.
stripCodePathRoot(x)stripCodePathRoot(x)
x |
A vector of code paths. |
The modified vector of code paths.
stripCodePathRoot("codes>reason>parent_feels");stripCodePathRoot("codes>reason>parent_feels");
This function maps the codes from multiple streams onto a primary stream.
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") )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") )
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 append or prepend the stream identifier before merging the dataframes together. |
sep |
When not specifying |
fill |
When expanding streams, whether to duplicate elements to fill
the resulting vector. Ignored if |
paddingValue |
The value to insert for rows when not filling (by default, filling carries over the value from the last preceding row that had a value specified). |
neverFill |
Columns to never fill regardless of whether fill
is |
compressFun |
If specified, when compressing streams, instead of pasting
elements together using separator |
compressFunPart |
A function to apply to the segments that are
automatically created; this can be passed instead of |
expandFun |
If specified, when expanding streams, instead of potentially
filling the new larger vector with elements (if |
carryOverAnchors |
Whether to carry over anchors for each source |
colNameGlue |
When appending or prepending stream identifiers, the character(s) to use as "glue" or separator. |
silent |
Whether to be silent ( |
The object with parsd sources, x, with the synchronization results
added in the $syncResults subobject.
### Get a directory with example sources examplePath <- file.path( system.file(package="rock"), 'extdata', 'streams' ); ### Parse the sources parsedSources <- 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 examples parsedSources$syncResults$qdt[ , c("streamB_Code3_streamB", "streamC_Code1_streamC") ];### Get a directory with example sources examplePath <- file.path( system.file(package="rock"), 'extdata', 'streams' ); ### Parse the sources parsedSources <- 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 examples parsedSources$syncResults$qdt[ , c("streamB_Code3_streamB", "streamC_Code1_streamC") ];
Sync (expand or compress) a vector
sync_vector( x, newLength, sep = " ", fill = TRUE, compressFun = NULL, expandFun = NULL, compressFunPart = NULL, silent = rock::opts$get("silent") )sync_vector( x, newLength, sep = " ", fill = TRUE, compressFun = NULL, expandFun = NULL, compressFunPart = NULL, silent = rock::opts$get("silent") )
x |
The vector |
newLength |
The new length |
sep |
When not specifying |
fill |
When expanding streams, whether to duplicate elements to fill
the resulting vector. Ignored if |
compressFun |
If specified, when compressing streams, instead of pasting
elements together using separator |
expandFun |
If specified, when expanding streams, instead of potentially
filling the new larger vector with elements (if |
compressFunPart |
A function to apply to the segments that are
automatically created; this can be passed instead of |
silent |
Whether to be silent or chatty. |
The synced vector
rock::sync_vector(letters[1:10], 15); rock::sync_vector(letters[1:10], 5);rock::sync_vector(letters[1:10], 15); rock::sync_vector(letters[1:10], 5);
Compress a vector or data frame
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") )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") )
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 pasting
elements together using separator |
compressFunPart |
A function to apply to the segments that are
automatically created; this can be passed instead of |
silent |
Whether to be silent or chatty. |
The compressed vector or data frame
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 );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
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") )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") )
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 fill
the resulting vector. Ignored if |
neverFill |
Columns to never fill regardless of whether fill is |
paddingValue |
The value to insert for rows when not filling (by default, filling carries over the value from the last preceding row that had a value specified). |
expandFun |
If specified, when expanding streams, instead of potentially
filling the new larger vector with elements (if |
silent |
Whether to be silent or chatty. |
The expanded vector
rock::syncing_vector_expand(letters[1:10], 15); rock::syncing_vector_expand(letters[1:10], 15, fill=FALSE);rock::syncing_vector_expand(letters[1:10], 15); rock::syncing_vector_expand(letters[1:10], 15, fill=FALSE);
Use this function to export a templated report for cognitive interviews. To embed it in an R Markdown file, use !!! CREATE rock::knit_codebook() !!!
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") )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") )
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. |
x, invisibly
### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example CI examplePath <- 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 );### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example CI examplePath <- 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 );
Use this function to export your codebook specification to a PDF file. To embed it in an R Markdown file, use !!! CREATE rock::knit_codebook() !!!
template_codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent") )template_codebook_to_pdf( x, file, author = NULL, headingLevel = 1, silent = rock::opts$get("silent") )
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. |
x, invisibly
### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example codebook data("exampleCodebook_1", package = "rock"); rock::template_codebook_to_pdf( exampleCodebook_1, file = tmpFile );### Use a temporary file to write to tmpFile <- tempfile(fileext = ".pdf"); ### Load an example codebook data("exampleCodebook_1", package = "rock"); rock::template_codebook_to_pdf( exampleCodebook_1, file = tmpFile );
Easily parse a vector into a character value
vecTxt( vector, delimiter = ", ", useQuote = "", firstDelimiter = NULL, lastDelimiter = " & ", firstElements = 0, lastElements = 1, lastHasPrecedence = TRUE ) vecTxtQ(vector, useQuote = "'", ...)vecTxt( vector, delimiter = ", ", useQuote = "", firstDelimiter = NULL, lastDelimiter = " & ", firstElements = 0, lastElements = 1, lastHasPrecedence = TRUE ) vecTxtQ(vector, useQuote = "'", ...)
vector |
The vector to process. |
delimiter, firstDelimiter, lastDelimiter
|
The delimiters
to 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 use the first respective last delimiters |
lastHasPrecedence |
If the vector is very short, it's possible that the
sum of firstElements and lastElements is larger than the vector length. In
that case, downwardly adjust the number of elements to separate with the
first delimiter ( |
... |
Any addition arguments to |
A character vector of length 1.
vecTxtQ(names(mtcars));vecTxtQ(names(mtcars));
This function wordwraps a source.
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") )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") )
input |
For |
output |
For |
length |
At how many characters to word wrap. |
removeNewlines |
Whether to remove all newline characters from the source before starting to clean them. Be careful: if the source contains YAML fragments, these will 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 where one utterance ends and the next one starts). By default, this is a line break, and only change this if you know what you are doing. |
A character vector.
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 text cat(exampleText); ### Show preprocessed example text cat( paste0( rock::wordwrap_source( exampleText ), collapse = "\n" ) );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 text cat(exampleText); ### Show preprocessed example text cat( paste0( rock::wordwrap_source( exampleText ), collapse = "\n" ) );
Wrap all elements in a vector
wrapVector(x, width = 0.9 * getOption("width"), sep = "\n", ...)wrapVector(x, width = 0.9 * getOption("width"), sep = "\n", ...)
x |
The character vector |
width |
The number of |
sep |
The glue with which to combine the new lines |
... |
Other arguments are passed to |
A character vector
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");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");
These functions write one or more source(s) from memory (as
loaded by load_source() or load_sources() to a file.
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") )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") )
x |
The source(s). |
output |
The filename (for |
encoding |
The encoding to use. |
preventOverwriting |
Whether to prevent against overwriting of the
file(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 |
Invisibly, the input (x), to enable chaining in pipes.
### Get path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Get a temporary file to write to tempFile <- tempfile(fileext = ".rock") ### For R versions below 4.1 loadedSource <- 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 path to example source examplePath <- system.file("extdata", package="rock"); ### Get a path to one example file exampleFile <- file.path(examplePath, "example-1.rock"); ### Get a temporary file to write to tempFile <- tempfile(fileext = ".rock") ### For R versions below 4.1 loadedSource <- 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
yaml_delimiter_indices(x)yaml_delimiter_indices(x)
x |
The character vector. |
A numeric vector.
yaml_delimiter_indices( c("not here", "---", "above this one", "but nothing here", "below this one, too", "---") ); ### [1] 2 6yaml_delimiter_indices( c("not here", "---", "above this one", "but nothing here", "below this one, too", "---") ); ### [1] 2 6