| Type: | Package |
| Title: | Solutions for Common Problems in Base R |
| Version: | 1.1.4 |
| Maintainer: | David Bosak <dbosak01@gmail.com> |
| Description: | Contains functions for solving commonly encountered problems while programming in R. This package is intended to provide a lightweight supplement to Base R, and will be useful for almost any R user. |
| License: | CC0 |
| Encoding: | UTF-8 |
| URL: | https://common.r-sassy.org,https://github.com/dbosak01/common |
| BugReports: | https://github.com/dbosak01/common/issues |
| Depends: | R (≥ 3.6.0) |
| Suggests: | knitr, rmarkdown, testthat (≥ 3.0.0), glue, box, rstudioapi |
| Enhances: | base |
| Imports: | utils |
| Config/testthat/edition: | 3 |
| RoxygenNote: | 7.3.3 |
| VignetteBuilder: | knitr |
| NeedsCompilation: | no |
| Packaged: | 2025-12-08 04:44:15 UTC; dbosa |
| Author: | David Bosak [aut, cre], Duong Tran [ctb] |
| Repository: | CRAN |
| Date/Publication: | 2025-12-08 06:30:06 UTC |
common: A set of useful functions
Description
Thecommon package is set of usefulfunctions that enhance base R. These functions make up forsome deficiencies in thebase package. For example,there are functions to sort a data frame by multiple columns,and manipulate data frame labels. These are common activities,and can be used in almost any R program.
Functions Included
The functions included in thecommon package areas follows:
v: A generalized NSE quoting function.sort.data.frame: An overload of the sortfunction for data frames.labels.data.frame: An overload of the labels functionfor data frames.%p%: An infix operator forpaste0().%eq%: An enhanced equality infix operator.roundup: A rounding function that matches SAS® software.Sys.path: A function to return the path of the current program.file.find: A function to search for a file on the file system.dir.find: A function to search for directories on the file system.find.names: A function to search for variable names on a data frame.copy.attributes: A function to copy column attributes from one dataframe to another.spaces: A function to create a string of blank spaces.supsc: A function to get UTF-8 superscript characters.subsc: A function to get UTF-8 subscript characters.symbol: A function to get UTF-8 symbol characters.changed: A function to identify changed values in a vector or data frame.source.all: A function to source an entire directory of R programs.
Author(s)
Maintainer: David Bosakdbosak01@gmail.com
Other contributors:
Duong Trantrand000@aol.com [contributor]
See Also
Useful links:
Report bugs athttps://github.com/dbosak01/common/issues
Check equality of two objects
Description
The goal of the%eq% operator is to return a TRUEor FALSE value when any two objects are compared. The function provides asimple, reliable equality check that allows comparingof NULLs, NA values, and atomic data types without error.
The function also allows comparingof data frames. It will return TRUE if all values in thedata frames are equal, and ignores differences in attributes.
Usage
x1 %eq% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Value
A single TRUE or FALSE value depending on whether the objects are equal.
See Also
Other operators:%ge%(),%gt%(),%le%(),%lt%(),%ne%(),%p%()
Examples
# Comparing of NULLs and NANULL %eq% NULL # TRUENULL %eq% NA # FALSENA %eq% NA # TRUE1 %eq% NULL # FALSE1 %eq% NA # FALSE# Comparing of atomic values1 %eq% 1 # TRUE"one" %eq% "one" # TRUE1 %eq% "one" # FALSE1 %eq% Sys.Date() # FALSE# Comparing of vectorsv1 <- c("A", "B", "C")v2 <- c("A", "B", "D")v1 %eq% v1 # TRUEv1 %eq% v2 # FALSE# Comparing of data framesmtcars %eq% mtcars # TRUEmtcars %eq% iris # FALSEiris %eq% iris[1:50,] # FALSE# Mixing it upmtcars %eq% NULL # FALSEv1 %eq% NA # FALSE1 %eq% v1 # FALSEPerform greater than or equal comparison between two objects
Description
The goal of the comparison operators is to return a TRUEor FALSE value when any two objects are compared. The operators provides asimple, reliable equality check that allows comparingof NULLs, NA values, and atomic data types without error. This operatorperforms a greater than or equal comparison.
For data frames, the operator will compare all values in all columns, and returna single TRUE if all values in the second data frame are greater than or equalto the corresponding values in the first data frame.
Usage
x1 %ge% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Details
Additional details...
Value
A single TRUE or FALSE value indicating the results of the comparison.
See Also
Other operators:%eq%(),%gt%(),%le%(),%lt%(),%ne%(),%p%()
Examples
# Comparing of NULLs and NANULL %ge% NULL # TRUENULL %ge% NA # FALSENA %ge% NA # TRUE1 %ge% NULL # FALSE1 %ge% NA # FALSE# Comparing of atomic values1 %ge% 1 # TRUE2 %ge% 1 # TRUE1 %ge% 2 # FALSE"one" %ge% "one" # TRUE1 %ge% "one" # FALSE1 %ge% Sys.Date() # FALSESys.Date() %ge% 1 # TRUE (Sys.Date() is a number)# Comparing of vectorsv1 <- c(0, 1, 2)v2 <- c(1, 2, 3)v3 <- c(2, 3, 4)v1 %ge% v1 # TRUEv1 %ge% v2 # FALSEv2 %ge% v1 # TRUEv3 %ge% v1 # TRUE# Comparing of data framesd1 <- data.frame(A = v1, B = v2)d2 <- data.frame(A = v2, B = v3)d1 %ge% d1 # TRUEd1 %ge% d2 # FALSEd2 %ge% d1 # TRUE# Mixing it upd1 %ge% NULL # FALSEv1 %ge% d1 # FALSE1 %ge% v1 # FALSEPerform greater than comparison between two objects
Description
The goal of the comparison operators is to return a TRUEor FALSE value when any two objects are compared. The operators provides asimple, reliable equality check that allows comparingof NULLs, NA values, and atomic data types without error. This operatorperforms a greater than comparison.
For data frames, the operator will compare all values in all columns, and returna single TRUE if all values in the second data frame are greater than thecorresponding values in the first data frame.
Usage
x1 %gt% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Value
A single TRUE or FALSE value indicating the results of the comparison.
See Also
Other operators:%eq%(),%ge%(),%le%(),%lt%(),%ne%(),%p%()
Examples
# Comparing of NULLs and NANULL %gt% NULL # FALSENULL %gt% NA # FALSENA %gt% NA # FALSE1 %gt% NULL # FALSE1 %gt% NA # FALSE# Comparing of atomic values1 %gt% 1 # FALSE2 %gt% 1 # TRUE1 %gt% 2 # FALSE"one" %gt% "one" # FALSE1 %gt% "one" # FALSE1 %gt% Sys.Date() # FALSESys.Date() %gt% 1 # TRUE (Sys.Date() is a number)# Comparing of vectorsv1 <- c(0, 1, 2)v2 <- c(1, 2, 3)v3 <- c(2, 3, 4)v1 %gt% v1 # FALSEv1 %gt% v2 # FALSEv2 %gt% v1 # TRUEv3 %gt% v1 # TRUE# Comparing of data framesd1 <- data.frame(A = v1, B = v2)d2 <- data.frame(A = v2, B = v3)d1 %gt% d1 # FALSEd1 %gt% d2 # FALSEd2 %gt% d1 # TRUE# Mixing it upd1 %gt% NULL # FALSEv1 %gt% d1 # FALSE1 %gt% v1 # FALSEPerform less than or equal comparison between two objects
Description
The goal of the comparison operators is to return a TRUEor FALSE value when any two objects are compared. The operators provides asimple, reliable equality check that allows comparingof NULLs, NA values, and atomic data types without error. This operatorperforms a less than or equal to comparison.
For data frames, the operator will compare all values in all columns, and returna single TRUE if all values in the second data frame are less than or equal tothe corresponding values in the first data frame.
Usage
x1 %le% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Details
Additional details...
Value
A single TRUE or FALSE value indicating the results of the comparison.
See Also
Other operators:%eq%(),%ge%(),%gt%(),%lt%(),%ne%(),%p%()
Examples
# Comparing of NULLs and NANULL %le% NULL # TRUENULL %le% NA # FALSENA %le% NA # TRUE1 %le% NULL # FALSE1 %le% NA # FALSE# Comparing of atomic values1 %le% 1 # TRUE2 %le% 1 # FALSE1 %le% 2 # TRUE"one" %le% "one" # TRUE1 %le% "one" # FALSE1 %le% Sys.Date() # TRUE (Sys.Date() is a number)# Comparing of vectorsv1 <- c(0, 1, 2)v2 <- c(1, 2, 3)v3 <- c(2, 3, 4)v1 %le% v1 # TRUEv1 %le% v2 # TRUEv2 %le% v1 # FALSEv2 %le% v3 # TRUE# Comparing of data framesd1 <- data.frame(A = v1, B = v2)d2 <- data.frame(A = v2, B = v3)d1 %le% d1 # TRUEd1 %le% d2 # TRUEd2 %le% d1 # FALSE# Mixing it upd1 %le% NULL # FALSEv1 %le% d1 # FALSE1 %le% v1 # FALSEPerform less than comparison between two objects
Description
The goal of the comparison operators is to return a TRUEor FALSE value when any two objects are compared. The operators provides asimple, reliable equality check that allows comparingof NULLs, NA values, and atomic data types without error. This operatorperforms a less than comparison.
For data frames, the operator will compare all values in all columns, and returna single TRUE if all values in the second data frame are less than thecorresponding values in the first data frame.
Usage
x1 %lt% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Value
A single TRUE or FALSE value indicating the results of the comparison.
See Also
Other operators:%eq%(),%ge%(),%gt%(),%le%(),%ne%(),%p%()
Examples
# Comparing of NULLs and NANULL %lt% NULL # FALSENULL %lt% NA # FALSENA %lt% NA # FALSE1 %lt% NULL # FALSE1 %lt% NA # FALSE# Comparing of atomic values1 %lt% 1 # FALSE2 %lt% 1 # FALSE1 %lt% 2 # TRUE"one" %lt% "one" # FALSE1 %lt% "one" # FALSE1 %lt% Sys.Date() # TRUE (Sys.Date() is a number)# Comparing of vectorsv1 <- c(0, 1, 2)v2 <- c(1, 2, 3)v3 <- c(2, 3, 4)v1 %lt% v1 # FALSEv1 %lt% v2 # TRUEv2 %lt% v1 # FALSEv2 %lt% v3 # TRUE# Comparing of data framesd1 <- data.frame(A = v1, B = v2)d2 <- data.frame(A = v2, B = v3)d1 %lt% d1 # FALSEd1 %lt% d2 # TRUEd2 %lt% d1 # FALSE# Mixing it upd1 %lt% NULL # FALSEv1 %lt% d1 # FALSE1 %lt% v1 # FALSECheck for inequality of two objects
Description
The goal of the%ne% operator is to return a TRUEor FALSE value when any two objects are compared. The function is theopposite of the equality operator. It returns a TRUE when the objectsare not equal.
This operator also allows comparingof data frames. It will return TRUE if any values in thedata frames are not equal, and ignores differences in attributes.
Usage
x1 %ne% x2Arguments
x1 | The first object to compare |
x2 | The second object to compare |
Value
A single TRUE or FALSE value depending on whether the objects arenot equal.
See Also
Other operators:%eq%(),%ge%(),%gt%(),%le%(),%lt%(),%p%()
Examples
# Comparing of NULLs and NANULL %ne% NULL # FALSENULL %ne% NA # TRUENA %ne% NA # FALSE1 %ne% NULL # TRUE1 %ne% NA # TRUE# Comparing of atomic values1 %ne% 1 # FALSE"one" %ne% "one" # FALSE1 %ne% "one" # TRUE1 %ne% Sys.Date() # TRUE# Comparing of vectorsv1 <- c("A", "B", "C")v2 <- c("A", "B", "D")v1 %ne% v1 # FALSEv1 %ne% v2 # TRUE# Comparing of data framesmtcars %ne% mtcars # FALSEmtcars %ne% iris # TRUEiris %ne% iris[1:50,] # TRUE# Mixing it upmtcars %ne% NULL # TRUEv1 %ne% NA # TRUE1 %ne% v1 # TRUEAn infix operator forpaste0()
Description
This function provides an infix operator for thepaste0 function to concatenate strings. The operatorwill concatenate a vector of one or more values. The functionalityis identical topaste0(), but more convenient to use in somesituations.
Usage
x %p% yArguments
x | A value for the left side of the paste infix operator. |
y | A value for the right side of the paste infix operator. |
Value
The concatenated or pasted value. No spaces will be insertedin between the values to paste. If a vector of values is supplied,a vector of pasted values will be returned.
See Also
Other operators:%eq%(),%ge%(),%gt%(),%le%(),%lt%(),%ne%()
Examples
# Paste together two stringsstr <- "Hello" %p% "World"str# [1] "HelloWorld"# Paste together number and stringstr <- 100 %p% " Kittens"str# [1] "100 Kittens"# Paste together two vectorsv1 <- c("A", "B", "C")v2 <- c(1, 2, 3)str <- v1 %p% v2str# [1] "A1" "B2" "C3"Returns the path of the current program
Description
A function that gets the full path of the currently runningprogram. If the function fails to retrieve the path for some reason,it will return a NULL. The function takes no parameters.
Usage
Sys.path()Value
The full path of the currently running program, or a NULL.
See Also
Other fileops:dir.find(),file.find(),source.all()
Examples
# Get current pathpth <- Sys.path()pth# [1] "C:/programs/myprogram.R"Identify changed values
Description
Thechanged function identifies changes in a vector ordata frame. The function is used to locate grouping boundaries. It willreturn a TRUE each time the current value is different from the previousvalue. Thechanged function is similar to the Base Rduplicatedfunction, except thechanged function will return TRUE even ifthe changed value is not unique.
Usage
changed(x, reverse = FALSE, simplify = FALSE)Arguments
x | A vector of values in which to identify changed values.Also accepts a data frame. In the case of a data frame, the functionwill use all columns. Input data can be any data type. |
reverse | Reverse the direction of the scan to identify the lastvalue in a group instead of the first. |
simplify | If the input data to the function is a data frame,the simplify option will return a single vector of indicator valuesinstead of a data frame of indicator values. |
Details
For a data frame,by default, the function will return another data frame with an equalnumber of change indicator columns. The column nameswill be the original column names, with a ".changed" suffix.
To collapsethe multiple change indicators into one vector, use the "simplify" option.In this case, the returned vector will essentially be an "or" operationacross all columns.
Value
A vector of TRUE or FALSE values indicating the grouping boundariesof the vector or data frame. If the input data is a data frame and the"simplify" parameter is FALSE, the return value will be a data frameof logical vectors describing changed values for each column.
Examples
# Create sample vectorv1 <- c(1, 1, 1, 2, 2, 3, 3, 3, 1, 1)# Identify changed valuesres1 <- changed(v1)# View resultsres1# [1] TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE# Create sample data framev2 <- c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B")dat <- data.frame(v1, v2)# View original data framedat# v1 v2# 1 1 A# 2 1 A# 3 1 A# 4 2 A# 5 2 A# 6 3 A# 7 3 B# 8 3 B# 9 1 B# 10 1 B# Get changed values for each columnres2 <- changed(dat)# View resultsres2# v1.changed v2.changed# 1 TRUE TRUE# 2 FALSE FALSE# 3 FALSE FALSE# 4 TRUE FALSE# 5 FALSE FALSE# 6 TRUE FALSE# 7 FALSE TRUE# 8 FALSE FALSE# 9 TRUE FALSE# 10 FALSE FALSE# Get changed values for all columnsres3 <- changed(dat, simplify = TRUE)# View resultsres3# [1] TRUE FALSE FALSE TRUE FALSE TRUE TRUE FALSE TRUE FALSE# Get last items in each group instead of firstres4 <- changed(dat, reverse = TRUE)# View resultsres4# v1.changed v2.changed# 1 FALSE FALSE# 2 FALSE FALSE# 3 TRUE FALSE# 4 FALSE FALSE# 5 TRUE FALSE# 6 FALSE TRUE# 7 FALSE FALSE# 8 TRUE FALSE# 9 FALSE FALSE# 10 TRUE TRUECopy attributes between two data frames
Description
A function to copy column attributes from onedata frame to another. The function will copy all attributes attachedto each column. The column order does not matter, and the data framesdo not need identical structures. The matching occurs by column name,not position. Any existing attributes on the target data framethat do not match the source data frame will be retained unaltered.
Usage
copy.attributes(source, target)Arguments
source | A data frame to copy attributes from. |
target | A data frame to copy attributes to. |
Value
The data frame in thetarget parameter, with updatedattributes fromsource.
See Also
Other overrides:labels.data.frame(),sort.data.frame()
Examples
# Prepare datadat1 <- mtcarsdat2 <- mtcars# Set labels for dat1labels(dat1) <- list(mpg = "Miles Per Gallon", cyl = "Cylinders", disp = "Displacement")# Copy labels from dat1 to dat2dat2 <- copy.attributes(dat1, dat2)# View resultslabels(dat2)# $mpg# [1] "Miles Per Gallon"## $cyl# [1] "Cylinders"## $disp# [1] "Displacement"Search for directories
Description
A function to find directories on the file system. The functionstarts from the directory specified in thepath parameter,and searches outward in a radiating patternfor the ending directory name in thepattern parameter.Theup anddown parameters define the scope of the search.Results are returned as a vector of full paths in the order encountered.This function has an advantage overlist.dirs in that it cansearch both up and down the file system, and limit the scope of the search.
Usage
dir.find(path = ".", pattern = NULL, up = 5, down = 2)Arguments
path | The directory to start searching from. Default is the currentworking directory. |
pattern | A full or partial name of the directory to find. If partial,use the question mark (?) or asterisk (*) characters to indicatethe missing piece. Default is NULL, which will return all directories. |
up | The number of levels above the base path to search. A value ofzero (0) means that you do not want to search up. A value of -1 meansyou do not want to include the base directory in the search results.Default is 5 levels up. |
down | The number of levels below the base path to search. A value ofzero (0) means that you do not want to search down. A value of -1 means youdo not want to include the base directory in the search results.Default is 2 levels down. |
Details
Thedir.find function attempts to find a directory based ona full or partial directory name. The directory name is passedon thepattern parameter.Thepattern accepts both the single character question markwild card (?), and the asterisk, multi-character wild card (*).Searches are case-insensitive.
Starting from the base path specified in thepath parameter,the function searchesboth above and below the base path in an alternatingpattern. The function will first search the base path, then up one level,then down one level, and so on. The boundaries ofthe search can be controlled by theup anddown parameters.
You can control whether or not you want the base directoryincluded in the results. To include this directory, ensure bothupanddown parameters are zero or greater. If either of theseparameters is set to -1, the base path will be excluded. For example,up = 3, down = 1 will search up three levels, and down one level.up = 3, down = 0 will search up three levels and not search down,but will include the base directory.up = 3, down = -1 will searchup three levels, not search down, and not include the base directory inthe results.
Value
A vector of one or more full directory paths that metthe search criteria. The paths in the vector are returnedin the order of matches, according to the search algorithm. That meansthe first directory found will be in position one, and the lastdirectory foundwill be at the end of the vector. A NULL is returned if nodirectories met the search criteria.
See Also
Other fileops:Sys.path(),file.find(),source.all()
Examples
# Search for a directory named "prod"file.find(pattern = "prod")# Search for a directory that starts with "dat"file.find(pattern = "dat*")# Search for a directory up onlyfile.find(pattern = "dat*", up = 3, down = 0)# Search for directories up only, skipping the current working directoryfile.find(pattern = "dat*", up = 3, down = -1)Search for files
Description
A function to find files on the file system. The functionstarts from the directory specified in thepath parameter,and searches outward in a radiating patternfor the file name in thepattern parameter.Results are returned as a vector of full paths in the order encountered.Theup anddown parameters define the scope of the search.This function has an advantage overlist.files in that it cansearch both up and down the file system, and limit the scope of the search.
Usage
file.find(path = ".", pattern = NULL, up = 3, down = 1)Arguments
path | The directory to start searching from. Default is the currentworking directory. |
pattern | A full or partial name of the file to find. If partial,use the question mark (?) or asterisk (*) characters to indicatethe missing piece. Default is NULL, which will return all files. |
up | The number of levels above the base path to search. A value ofzero (0) means that you do not want to search up. A value of -1 meansyou do not want to include the base directory in the search results.Default is 3 levels up. |
down | The number of levels below the base path to search. A value ofzero (0) means that you do not want to search down. A value of -1 means youdo not want to include the base directory in the search results.Default is 1 level down. |
Details
Thefile.find function attempts to find a file based ona full or partial file name. The file name is passedon thepattern parameter.Thepattern accepts both the single character question markwild card (?), and the asterisk multi-character wild card (*).Searches are case-insensitive.
Starting from the base path specified in thepath parameter,the function searchesboth above and below the base path in an alternatingpattern. The function will first search the base path, then up one level,then down one level, and so on. The boundaries ofthe search can be controlled by theup anddown parameters.
You can control whether or not you want files from the base directoryincluded in the results. To include these files, ensure bothupanddown parameters are zero or greater. If either of theseparameters is set to -1, the base path will be excluded. For example,up = 3, down = 1 will search up three levels, and down one level.up = 3, down = 0 will search up three levels and not search down,but will include the base directory.up = 3, down = -1 will searchup three levels, not search down, and not include the base directory inthe results.
Value
A vector of one or more full file paths that met the search criteria.The paths in the vector are returnedin the order of matches, according to the search algorithm. That meansthe first file found will be in position one, and the last file foundwill be at the end of the vector. A NULL is returned if nofiles met the search criteria.
See Also
Other fileops:Sys.path(),dir.find(),source.all()
Examples
# Search for a file named "globals.R"file.find(getwd(), "globals.R")# Search for Rdata filesfile.find(getwd(), "*.Rdata")# Search for Rdata files up onlyfile.find(getwd(), "*.Rdata", up = 3, down = 0)# Search for Rdata files up only, skipping the current working directoryfile.find(getwd(), "*.Rdata", up = 3, down = -1)Search for names
Description
A function to search for variable names in a data.frame or tibble.The function features wild card pattern matching, start and endboundaries, and names to exclude.
Usage
find.names( x, pattern = NULL, exclude = NULL, start = NULL, end = NULL, ignore.case = TRUE)Arguments
x | A data frame or tibble whose names to search. Parameter alsoaccepts a character vector of names. |
pattern | A vector of patterns to search for. The asterisk (*)and question mark (?) characters may be used to indicate partial matches. |
exclude | A vector of patterns to exclude from the search results.The asterisk (*)and question mark (?) characters may be used to indicate partial matches. |
start | A variable name or position to start the search. Default is 1. |
end | A variable name or position to end the search. Default is thelength of the name vector. |
ignore.case | Whether to perform a case sensitive or insensitivesearch. Valid values are TRUE and FALSE. Default is TRUE. |
Value
A vector of variable names that met the search criteria.
Examples
# Show all names for referencenames(mtcars)# [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"# Names that start with "c"find.names(mtcars, "c*")# [1] "cyl" "carb"# Names that start with "c" or "d"find.names(mtcars, c("c*", "d*"))# [1] "cyl" "carb" "disp" "drat"# Names between "disp" and "qsec"find.names(mtcars, start = "disp", end = "qsec")# [1] "disp" "hp" "drat" "wt" "qsec"# Names that start with "c" or "d" after position 5find.names(mtcars, c("c*", "d*"), start = 5)# [1] "carb" "drat"# Names between "disp" and "qsec" excluding "wt"find.names(mtcars, start = "disp", end = "qsec", exclude = "wt")# [1] "disp" "hp" "drat" "qsec"Get or set labels for a data frame
Description
Thelabels function extracts all assigned labels from adata frame, and returns them in a named list. The function alsoassigns labels from a named list. This function is a data frame-specificimplementation of the Base Rlabels function.
Usage
## S3 method for class 'data.frame'labels(object, ...)labels(x) <- valueArguments
object | A data frame or tibble. |
... | Follow-on parameters. Required for generic function. |
x | A data frame or tibble |
value | A named list of labels. The labels must be quoted strings. |
Details
If labels are assigned to the "label" attributes of the data framecolumns, thelabels function will extract those labels. Thefunction will return the labels in a named list, where the namescorrespond to the name of the column that the label was assigned to.If a column does not have a label attribute assigned, that columnwill not be included in the list.
When used on the receiving side of an assignment, the function will assignlabels to a data frame. The labels should be in a named list, whereeach name corresponds to the data frame column to assign the label to.
Finally, if you wish to clear out the label attributes, assigna NULL value to thelabels function.
Value
A named list of labels. The labels must be quoted strings.
See Also
Other overrides:copy.attributes(),sort.data.frame()
Examples
# Take subset of datadf1 <- mtcars[1:10, c("mpg", "cyl")]# Assign labelslabels(df1) <- list(mpg = "Mile Per Gallon", cyl = "Cylinders")# Examine attributesstr(df1)# 'data.frame':10 obs. of 2 variables:# $ mpg: num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2# ..- attr(*, "label")= chr "Mile Per Gallon"# $ cyl: num 6 6 4 6 8 6 8 4 4 6# ..- attr(*, "label")= chr "Cylinders"# View assigned labelslabels(df1)# $mpg# [1] "Mile Per Gallon"## $cyl# [1] "Cylinders"# Clear labelslabels(df1) <- NULL# Display Cleared Labelslabels(df1)# list()Rounds numbers up
Description
A function that rounds positive numbers up when the last digitis a 5. For negative numbers ending in 5, the function actually rounds down."Round away from zero" is the most accurate description of this function.
Usage
roundup(x, digits = 0)Arguments
x | A vector of values to round. Also accepts a data frame. In thecase of a data frame, the function will round all numeric columns. |
digits | A number of decimal places to round to. Default is zero. |
Value
The rounded data vector.
Examples
# Round to evenround(2.4) # 2round(2.5) # 2round(-2.5) # -2round(2.6) # 3# Round uproundup(2.4) # 2roundup(2.5) # 3roundup(-2.5) # -3roundup(2.6) # 3Sorts a data frame
Description
An overload to the Base Rsort function fordata frames. Allows multiple columns to be sorted easily. Alsoallows you to control the sort direction for each column independently.
Usage
## S3 method for class 'data.frame'sort( x, decreasing = FALSE, ..., by = NULL, ascending = TRUE, na.last = TRUE, index.return = FALSE)Arguments
x | The input data frame to sort. |
decreasing | This parameter was added to conform to the S3 genericmethod signature of the |
... | This parameter is required for the generic method signature.Anything passed on it will be ignored. |
by | A vector of column names to sort by. If this parameteris not supplied, the function will sort by all columns in orderfrom left to right. |
ascending | A vector of TRUE or FALSE values correspondingto the variables on the |
na.last | Whether to put NA values first or last in the sort. If TRUE,NA values will sort to the bottom. If FALSE, NA values will sort to thetop. The default is TRUE. |
index.return | Whether to return the sorted data frame or a vectorof sorted index values. If this parameter is TRUE, the functionwill return sorted index values. By default, the parameter is FALSE,and will return the sorted data frame. |
Value
The function returns either a sorted data frame or asorted vector of row index values, depending on the value of theindex.return parameter. Ifindex.return is FALSE,the function will return the sorted data frame.If theindex.return parameter is TRUE, it will return a vectorof row indices.
See Also
Other overrides:copy.attributes(),labels.data.frame()
Examples
# Prepare unsorted sample datadt <- mtcars[1:10, 1:3]dt# mpg cyl disp# Mazda RX4 21.0 6 160.0# Mazda RX4 Wag 21.0 6 160.0# Datsun 710 22.8 4 108.0# Hornet 4 Drive 21.4 6 258.0# Hornet Sportabout 18.7 8 360.0# Valiant 18.1 6 225.0# Duster 360 14.3 8 360.0# Merc 240D 24.4 4 146.7# Merc 230 22.8 4 140.8# Merc 280 19.2 6 167.6# Sort by mpg ascendingdt1 <- sort(dt, by = "mpg")dt1# mpg cyl disp# Duster 360 14.3 8 360.0# Valiant 18.1 6 225.0# Hornet Sportabout 18.7 8 360.0# Merc 280 19.2 6 167.6# Mazda RX4 21.0 6 160.0# Mazda RX4 Wag 21.0 6 160.0# Hornet 4 Drive 21.4 6 258.0# Datsun 710 22.8 4 108.0# Merc 230 22.8 4 140.8# Merc 240D 24.4 4 146.7# Sort by mpg descendingdt1 <- sort(dt, by = "mpg", ascending = FALSE)dt1# mpg cyl disp# Merc 240D 24.4 4 146.7# Datsun 710 22.8 4 108.0# Merc 230 22.8 4 140.8# Hornet 4 Drive 21.4 6 258.0# Mazda RX4 21.0 6 160.0# Mazda RX4 Wag 21.0 6 160.0# Merc 280 19.2 6 167.6# Hornet Sportabout 18.7 8 360.0# Valiant 18.1 6 225.0# Duster 360 14.3 8 360.0# Sort by cyl then mpgdt1 <- sort(dt, by = c("cyl", "mpg"))dt1# mpg cyl disp# Datsun 710 22.8 4 108.0# Merc 230 22.8 4 140.8# Merc 240D 24.4 4 146.7# Valiant 18.1 6 225.0# Merc 280 19.2 6 167.6# Mazda RX4 21.0 6 160.0# Mazda RX4 Wag 21.0 6 160.0# Hornet 4 Drive 21.4 6 258.0# Duster 360 14.3 8 360.0# Hornet Sportabout 18.7 8 360.0# Sort by cyl descending then mpg ascendingdt1 <- sort(dt, by = c("cyl", "mpg"), ascending = c(FALSE, TRUE))dt1# mpg cyl disp# Duster 360 14.3 8 360.0# Hornet Sportabout 18.7 8 360.0# Valiant 18.1 6 225.0# Merc 280 19.2 6 167.6# Mazda RX4 21.0 6 160.0# Mazda RX4 Wag 21.0 6 160.0# Hornet 4 Drive 21.4 6 258.0# Datsun 710 22.8 4 108.0# Merc 230 22.8 4 140.8# Merc 240D 24.4 4 146.7Source all programs in a directory
Description
A function to source all programs in a specified directory.The function will run each R program file in the directory, and thenreturn a data frame of results of the run.
Usage
source.all(path = ".", pattern = NULL, exclude = NULL, isolate = TRUE)Arguments
path | The directory to source programs from. Default is the currentworking directory. |
pattern | A full or partial name of the programs to source. If partial,use the question mark (?) or asterisk (*) characters to indicatethe missing piece(s). Default is NULL, which will return all programs.You may pass multiple patterns as a vector. In that case, the functionwill perform an "or" operation on each pattern. Note that it is not necessaryto include the ".R" file extension in your patterns. It is assumed that allsource files have a ".R" extension. |
exclude | A vector of patterns to exclude from the included programs.The exclusion patterns can be the names of specific programs or a wild cardexclusion. The asterisk (*)and question mark (?) characters may be used to indicate partial matches.Similar to the "pattern" parameter, the ".R" file extension can be ignored. |
isolate | Whether to isolate each source call to its own environment.Valid values are TRUE, FALSE, or an environment to run in. If the isolateparameter is FALSE, the programs will run in the global environment. Defaultis TRUE. |
Details
Thesource.all function attempts to run all programs in a directory.This function is useful for batch runs. It has parameters to controlwhich programs are run or not run. By default, the function will runall programs in the working directory. You can use the "pattern" and"exclude" parameters to specify individual program names, or wild card matches.Inclusion and exclusion patterns are case-insensitive.
Note that the function will run all programs, regardless of any errors.Errors will be indicated in the "Status" and "Message" columns of the resultdataset.
Value
A data frame of the results of the source operation. Thedata frame will show each file sourced, the time started, the time ended,the status, and any error messages. The status value is either 0 (no errors)or 1 (errors).
Result Dataset
Thesource.all function returns a dataset showing the results of thesource operation. There will be one row for each program executed. Thereturn dataset has the following columns:
Filename: The name of the program.
StartTime: The date and time execution started.
EndTime: The date and time execution ended.
Status: A numeric value indicating whether or notthe program returned errors or warnings. A zero (0) value indicates thatno errors occurred. A one (1) value indicates that an erroroccurred. Warnings can also be generated along with an error, butthe status will still be one (1). A two (2) value indicatesthat warnings occurred but no errors. Note that capture of warningsis less reliable than the capture of errors. It is possible that a programmay generate a warning and still return a zero (0) status. If you want toensure that warnings are detected, convert them to errors with
options(warn = 2).Message: If errors or warnings are returned from the program,they will be shown in this column. Multiple messages will be separatedwith a semi-colon (;) and a carriage return.
In addition to the information shown above, the results dataset will haveattributes assigned with the parameter values passed to the function. Thoseattributes can be observed with the Base Rattributes() function.
Source Isolation
Multiple programs running in the same environment have a risk of conflictingvariables or data. Variables created by the first program can possibly interferewith the running of the next program. Or they could conflict with variablesin the global environment. To avoid such conflicts, each programis run in its own environment by default.isolate = TRUE starts each programwith a clean workspace, and is the best choice for running programs inbatch.
There may be situations, however, where you do not want to isolate thesource calls. For example, if you are loading functions from a utilitylibrary, you may actually wanted them loaded into the global environmentso they can by accessed by you or your programs. In this case, set the"isolate" parameter to FALSE.
Lastly, there may be situations where you want to intentionally share anenvironment, or extract values create by the running programs.In this case, you can instantiate a new environmentyourself, and pass that to the "isolate" parameter instead of TRUE or FALSE.Note that this environment will be shared by all programs, but will not haveaccess to the global environment.
See Also
Other fileops:Sys.path(),dir.find(),file.find()
Examples
# Create temp directorytmp <- tempdir()# Write program 1p1 <- file(file.path(tmp, "prog1.R"))writeLines("print('Hello from program 1')", p1)close(p1)# Write program 2p2 <- file(file.path(tmp, "prog2.R"))writeLines("stop('Error from program 2')", p2)close(p2)# Write program 3p3 <- file(file.path(tmp, "prog3.R"))writeLines("print('Hello from program 3')", p3)close(p3)# Example #1: Run all programsres1 <- source.all(tmp)# [1] "Hello from program 1"# [1] "Hello from program 3"# View resultsres1# Filename StartTime EndTime Status Message# 1 prog1.R 2024-03-05 10:12:04 2024-03-05 10:12:04 0 Success# 2 prog2.R 2024-03-05 10:12:04 2024-03-05 10:12:04 1 Error from program 2# 3 prog3.R 2024-03-05 10:12:04 2024-03-05 10:12:04 0 Success#' # Example #2: Exclusion criteriares2 <- source.all(tmp, exclude = "prog2")# [1] "Hello from program 1"# [1] "Hello from program 3"# View resultsres2# Filename StartTime EndTime Status Message# 1 prog1.R 2024-03-05 10:13:24 2024-03-05 10:13:24 0 Success# 2 prog3.R 2024-03-05 10:13:24 2024-03-05 10:13:24 0 Success# Example #3: Inclusion criteriares3 <- source.all(tmp, pattern = "*2")# View resultsres3# Filename StartTime EndTime Status Message# 1 prog2.R 2024-03-05 10:16:41 2024-03-05 10:16:41 1 Error from program 2# View attributesattributes(res3)# $names# [1] "Filename" "StartTime" "EndTime" "Status" "Message"## $class# [1] "data.frame"## $row.names# [1] 1## $path# [1] "C:\Users\dbosa\AppData\Local\Temp\RtmpGAXYJl"## $pattern# [1] "*2.R"## $errors# [1] 1Creates a string of blank spaces
Description
A function to create a string of some number of blank spaces.This function is useful when trying to align things.
Usage
spaces(num)Arguments
num | The desired number of spaces. |
Value
A single character vector of blank spaces.
Examples
# Create spacesspaces(10)# [1] " "# Use spaces to separate somethingstr <- "Left" %p% spaces(40) %p% "Right"str# [1] "Left Right"Converts a string to UTF-8 subscript
Description
Thesubsc function translates a normal character to a UTF-8subscript character. The function can be used togenerate subscripts for many common characters. Allnumeric characters and some lower case letters have UTF-8 subscripts.There are no upper case subscript letters.This function is usefulbecause it saves you from having to look up the subscript charactercode, or copy and paste from the internet. If a correspondingsubscript character code does not exist, a question markwill be returned for that character.
Usage
subsc(x)Arguments
x | A string to be converted to subscript. |
Value
The subscript version of the string passed to the function,if one exists. Otherwise, a question mark will be returned.
See Also
Examples
# Date stringpaste0("December 5", subsc("th"))# Chemistrypaste0("H", subsc("2"), "SO", subsc("4"))Converts a string to UTF-8 superscript
Description
Thesupsc function translates a normal character to a UTF-8superscript character. The function can be used togenerate superscripts for many common characters. Most alphabeticand numeric characters have UTF-8 superscripts. This function is usefulbecause it saves you from having to look up the superscript charactercode, or copy and pasting from the internet. If a correspondingsuperscript character code does not exist, a question markwill be returned for that character.
Usage
supsc(x)Arguments
x | A string to be converted to superscript. |
Value
The superscript version of the string passed to the function,if one exists. Otherwise, a question mark will be returned.
See Also
Examples
# Single letterpaste0(supsc("a"), "Footnote")# Single numberpaste0(supsc("1"), "Footnote")# Character stringpaste0("December 5", supsc("th"))# Formulapaste0("x", supsc("(a+1)"))Gets UTF-8 symbol characters
Description
Thesymbol function gets UTF-8 symbol characters. Youcan call this function to look up trademarks, Greek letters,and mathematical operators. The function uses HTML entitykeywords to indicate which symbol to return. You may pass more thanone keyword in a single call to get a combined result. Any characters notrecognized as a keyword will be left alone. Characters surrounded bysquare brackets ([]) will be subscripted. Characters surrounded by squarebrackets and prefixed with an up arrow (^[]) will be superscripted.
Usage
symbol(keyword)Arguments
keyword | A symbol keyword. This keyword follows HTML conventions. SeetheKeywords section for a complete list of all supported keywords. |
Value
The requested UTF-8 symbol character or characters.
Keywords
The following symbol keywords are available:
Trademark and Copyright: copy, reg, trade
Financial: cent, euro, pound, rupee, ruble, yen, yuan
Mathmatical: asymp, bcong, cong, coprod, empty, fnof,ge, int, Int, infin, le, ncong, ne, not, part, plusmn,prod, radic, sime, sum
Logical: and, cap, cup, comp, cuvee, cuwed, exist,forall, fork, isin, nexist, ni, notin,notni, nsub, nsup, or, sub, sup, xcap, xcup, xvee, xwedge
Greek uppercase letters: Alpha, Beta, Gamma, Delta, Epsilon,Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu, Nu, Xi, Omicron, Pi, Rho,Sigma, Tau, Upsilon, Phi, Chi, Psi, Omega
Greek lowercase letters: alpha, beta, gamma, delta, epsilon,zeta, eta, theta, iota, kappa, lambda, mu, nu, xi, omicron, pi, rho,sigma, tau, upsilon, phi, chi, psi, omega
Arrows: rarr, larr, barr, uarr, darr, harr, rArr, lArr, uArr, dArr, hArr
Other Symbols: dagger, ddagger, deg, permil, pertenk, sect
See Also
Examples
# Trademark symbolsymbol("My Companytrade")# Registered Trademark symbolsymbol("My Companyreg")# Dagger symbol concatenatedpaste0(symbol("dagger"), "My footnotes")# Alpha squaredsymbol("alpha^[2]")# Greek Symbolssymbol("SigmaPsiZeta")# Useful Math Symbolssymbol("asymp ge le ne plusmn empty fnof radic sum")# Useful Logical Symbolssymbol("forall isin notin cup cap and or")# Chemistrysymbol("2H[2] + O[2] barr 2H[2]O")Combine unquoted values
Description
A function to quote and combine unquoted values.The function will return a vector of quoted values. This functionallows you to use non-standard evaluation for any parameterthat accepts a string or vector of strings.
Usage
v(...)Arguments
... | One or more unquoted values. |
Value
A vector of quoted values.
Examples
# Combine unquoted valuesv(var1, var2, var3)# [1] "var1" "var2" "var3"# Data frame subsetdat <- mtcars[1:5, v(mpg, cyl, disp)]dat# mpg cyl disp# Mazda RX4 21.0 6 160# Mazda RX4 Wag 21.0 6 160# Datsun 710 22.8 4 108# Hornet 4 Drive 21.4 6 258# Hornet Sportabout 18.7 8 360# Data frame sortdat2 <- sort(dat, by = v(cyl, mpg))dat2# mpg cyl disp# Datsun 710 22.8 4 108# Mazda RX4 21.0 6 160# Mazda RX4 Wag 21.0 6 160# Hornet 4 Drive 21.4 6 258# Hornet Sportabout 18.7 8 360