Note: -*- Encoding: utf-8 -*-
Type: Package
Title: Charles's Utility Function using Formula
Version: 1.9
Date: 2023-03-22
Author: Charles-Édouard Giguère
Maintainer: Charles-Édouard Giguère <ce.giguere@gmail.com>
Depends: R (≥ 4.2.0)
Imports: openxlsx, xtable, DT, lmerTest, nlme, haven, dplyr, clipr
Description: Utility functions that provides wrapper to descriptive base functions like cor, mean and table. It makes use of the formula interface to pass variables to functions. It also provides operators to concatenate (%+%), to repeat (%n%) and manage character vectors for nice display.
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
Encoding: UTF-8
LazyLoad: TRUE
URL: https://github.com/giguerch/CUFF
NeedsCompilation: no
Packaged: 2023-03-23 11:28:49 UTC; gigc2
Repository: CRAN
Date/Publication: 2023-03-23 11:52:04 UTC

Extract and format coefficients table

Description

This function extract coefficients tables from common statistical model (lm/glm/lme/lmer/t-test) and format them.

Usage

cf(x, addci = TRUE, pv.style = 1, signif = 2, expcf, ...)

Arguments

x

x is a lm/glm/lme/lmer/t.test model

addci

Logical value that tells R to add a 95% confidence interval to the output. True by default.

pv.style

Integer specifying the style (1 or 2) of p-value formatting. See help(pv) for details

signif

Either an integer specifying the number of significant digits or a dimension 3 vector for respectively the estimate, standard error and t-value

expcf

Logical value that tells R to add exponentiated value of estimate. Set to FALSE except if the model specifies a logistic regression (family = binomial)

...

Not used yet

Value

Returns a data.frame of formatted characters of the coefficient table.

Author(s)

Charles-Édouard Giguère

Examples

lm1 <- lm(Sepal.Length ~ Species, iris)
cf(lm1)

Send to clipboard

Description

This is a function that sends a table-like object to the clipboard to paste it quickly on an external program.

Usage

clip(x, sep = "\t", row.names = FALSE, quote = FALSE, ...)

Arguments

x

x is a table a matrix or a data.frame to send to clipboard

sep

Type of separator for the output

row.names

Logical value (T/F) to include or exclude row names

quote

logical value to print or exclude quotation marks.

...

other arguments passed to write.table function

Value

No output. The results is printed to the clipboard.

Author(s)

Charles-Édouard Giguère


Bivariate correlations

Description

This is a function that creates correlation matrix objects that can be printed with the corresponding N and p-values. It is a wrapper for cor and cor.test.

Usage

correlation(x, y = NULL, method = "pearson",
            alternative = "two.sided", exact = NULL,
            use = "pairwise.complete.obs",
            continuity = FALSE, data = NULL)
## S3 method for class 'corr'
print(x, ... , toLatex = FALSE, cutstr = NULL, toMarkdown = FALSE)

Arguments

x

x is a matrix/data.frame or a formula defining which variable to use in the correlation matrix (see details).

y

y is a matrix/data.frame to correlate against x. If x is a formula y is passed to data argument

method

Method used to compute correlations.

alternative

Unilateral (one.sided) test or bilateral (two.sided) test. See help(cor) for more details.

exact

Logical value to know if a p.value is exact or asymptotic. See help(cor) for more details.

use

Methods to deal with missing values.

continuity

Logical value to know if continuity correction must be used. See help(cor) for more details.

...

Unused in this function

data

data.frame to use in conjuction with formula

toLatex

Logical value to know if output displayed as a latex tabular environment.

cutstr

Optional digits that cut the length of variable names

toMarkdown

Logical value to know if output should be displayed as a markdown table for report

Value

Returns a list with correlations, N for each pair of correlations and p.value for each correlations.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
X=rnorm(10)
Y=rnorm(10)
correlation(cbind(X,Y))

Crosstabs

Description

Functions to display (2 x 2) contingency table

Usage

cross(x, ...)

Arguments

x

Object of type table or formula, vector to tabulate

...

Arguments passed to table of xtabs

Details

The xtab functions corrects the inability to deal with missing values in the original xtabs that comes with R base.

Value

The cross methods returns an object of type cross with the original table and the marginal percentages by row and by column. A print methods is associated with a cross object. xtab returns an object of type table (see details). Total returns a sum with na.rm=TRUE by default and replaces NA with 0.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
### example of crosstabs
cr1 <- cross( ~ N + P, npk)
print(cr1, test = c("chisq.test", "fisher.test"))

Frequencies

Description

Functions to display frequency

Usage

freq(x, y = NULL, ..., labels = NULL, data = NULL)
## S3 method for class 'frequencies'
print(x, ..., toLatex = FALSE)

Arguments

x

Object of type formula, matrix or data.frame

y

If x is a formula,y or data contains the data from x or are set to NULL if the variables are in the main environment

...

used for compatibility

labels

Optional vector of labels the same length as the dimension of x or the number of variables in formula.

data

see y for details

toLatex

Logical value that indicates if the print methods should return a tabular latex environment to use with Sweave or knitr.

Details

The freq methods returns an object of type frequencies object with a print methods associated.

Value

An object of type "frequencies" that is a list of matrix containing the frequencies the % and the % with missing value.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
### example of crosstabs
fr1 <- freq( ~ N + P, npk, c("Nitrogen", "Phosphate"))
fr1
### To use with sweave or knitr.
print(fr1, toLatex = TRUE)

Fonctions pour ajouter les pourcentages dans les tables

Description

La fonction retourne une table avec le contenu en caractères de la fréquence et du pourcentage

Usage

ftab(xt, margin = seq_along(dim(xt)), fmt = "%d (%5.1f %%)", quiet = FALSE)

Arguments

xt

Une table de contingence généré avec table ou xtabs

margin

Si 2x2, est que le pourcentage est en ligne (1) ou en colonne(2) ou total (1:2). Par défaut, pourcentage total. Ne sert à rien lorsque le tableau est à une dimension.

fmt

format d'affichage

quiet

Valeur logique qui indique si le tableau est imprimé

Value

Retourne une table avec le contenu en caractères de la frequence et du pourcentage

Author(s)

Charles-Édouard Giguère

Examples

ex <- as.table(cbind(3:4,5:6))
ftab(ex,2)

function to compute mean and sd into a single string

Description

Methods that estimates a mean and sd and stores it into a single string

Usage

 meansd(x, digits = c(1, 1)) 

Arguments

x

A vector of numeric value

digits

digits for respectively the mean and sd. If a single value is entered it applies to mean and sd

Value

Returns a string containing mean and sd with entered digit precisions.

Author(s)

Charles-Édouard Giguère

Examples

xf(Sepal.Width ~ Species, iris, meansd)

Palette de couleurs

Description

A 10 color palette.

Usage

pal_CUFF(n = 10, pal = "CUFF")

Arguments

n

Integer indicating the number of color desired (1-10)

pal

The only value possible for now is CUFF

Value

Returns a vector of color.

Author(s)

Charles-Édouard Giguère

Examples

pal_CUFF(3)

Crosstabs print methods

Description

Functions to display (2 x 2) contingency table

Usage

## S3 method for class 'cross'
print(x, ..., test = "chisq.test", export = NULL)

Arguments

x

Object of type cross to print

...

Unused arguments

test

list of statistical tests (as character vector) passed to the 2x2 table. By default, test is set to "chisq.test" which performs a khi-square test with Yates continuity correction.

export

Either "pdf" or "xlsx" or NUll. Crosstab is flushed into either a pdf using latex or an Excel spreadsheet using package openxlsx

Details

Export to "pdf", "xlsx" open the crosstabs in the corresponding formats.

Value

Print methods associated with the cross object.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
### example of crosstabs
cr1 <- cross( ~ N + P, npk)
print(cr1, test = c("chisq.test", "fisher.test"))

Format p-values

Description

This is a function that format p-values for publication.

Usage

pv(p, style = 1)

Arguments

p

A vector of p-values

style

By default (1), formatting according to APA style guide version 6

Details

Value

returns a character vector of formatted p-value.

Author(s)

Charles-Édouard Giguère

Examples

p <- c(0.1563,0.0122,0.00001) 
pv(p)

Utility functions to treat characters

Description

Function %+% paste characters with other characters pairwise. Function %n% is used to repeat a character n time. Function numtostr converts numeric to a string in a nice format.

Usage

x %+% y
x %n% y
numtostr(x,nch,digits=4)

Arguments

x

Character vector or a numeric vector for numtostr functions

y

Character vector

nch

(Optionnal) length of the resulting character vector

digits

Number of digits in the resulting strings

Value

Function %+% is an operator that shortens paste(x, y, sep="") see help(paste) for more options. Function %n% returns the character vector x repeated y times. If both x and y are vector each element of x are applied to each element of y. Function numtostr converts numerical vector to a character vector using a nice format.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
"Hello " %+% "world."
cat(" " %n%  c(rep(1,9),2) %+% 1:10,fill=TRUE)
### Returns a * because specified length of character is unsufficient. 
numtostr(9048948449.94948,nch=8)


sum weighted on the number of non-missing values

Description

Methods that estimates a sum weighted by the number of non-missing values

Usage

 ## S3 method for class 'n'
sum(x,n = 1, ...) 

Arguments

x

A vector of values possibly containing missing values.

n

Minimum number of valid values

...

extra parameters to sum

Details

sum(x,n) = mean(x) * length(x) / n.valid(x)

Value

sum.n returns the values of the weighted sum.

Author(s)

Charles-Édouard Giguère

Examples

sum.n(c(1, 2, NA, NA), n = 2)
### [1] 6
sum.n(c(1, NA, NA, NA), n = 2)
### [1] NA

Export into a csv file with a format csv companions for factors

Description

This functions export a data frame into a csv file with a csv companion file containing formats to properly reimport data into R.

Usage

column_types(data)
to_csv(data, file)

Arguments

data

A data.frame containing data to export

file

Name of the csv file to export to

Value

returns nothing

Author(s)

Charles-Édouard Giguère

Examples

# to_csv(iris,"iris.csv")

view methods

Description

Wrapper to DT::datatable.

Usage

view(x, ...)

Arguments

x

x is a matrix/data.frame/table format for viewing

...

arguments passed to datatable

Value

Export data to be viewed as a web page. See help(datatable, package = "DT") for further details.

Author(s)

Charles-Édouard Giguère

Examples

view(iris)
### add filter on top.
view(iris, filter = "top")

Methods that apply a function across a levels of one or more factors

Description

Methods that apply a function across a levels of one or more factors. It works like aggregate but returns a table instead. It also has a useNA options that adds NA as a level before applying the function.

Usage

xf(formula, data, FUN, ..., subset, na.action = na.omit, useNA = FALSE, addmargins = TRUE)

Arguments

formula

Formula defining the variables. On the left is the variable we are applying the function to, on the right, variables defining levels of the tables

data

Data.frame containing the variables

FUN

The function to apply to each subset of data

...

extra parameters to FUN

subset

Vectors defining a subset of data.frame (see help(aggregate)).

na.action

Action functions to deal with NA in data file

useNA

Make NA a level of the factors (if any)

addmargins

Add function applied to the margins of each category

Value

xf returns an object "xf" that behaves like a table with all associated methods.

Author(s)

Charles-Édouard Giguère

Examples

res <- xf(Sepal.Length~Species,iris,mean)
barplot(res)

Crosstabulations using formula

Description

Functions to create contingency table using formula

Usage

xtab(formula, data, useNA = FALSE, exclude = c(NA,NaN), miss.char = "-",
     na.action = na.exclude, subset = NULL, sparse = FALSE,
     drop.unused.levels = FALSE)
Total(x)

Arguments

formula

Object of class cross to be printed

data

data frame to use with formula

useNA

logical values to add NA to the levels in the table

exclude

levels to exclude from table

miss.char

Character to replace NA

na.action

methods to deal with NA

subset

subset to use in data

sparse

see help(xtabs) for details

drop.unused.levels

logical values indicating whether we drop empty levels

x

numerical vector

Details

The xtab functions corrects the inability to deal with missing values in the original xtabs that comes with R base. Total is a utility function to use in conjunction with addmargins instead of sum.

Value

xtab returns an object of type table (see details). Total returns a sum with na.rm=TRUE by default and replaces NA with 0.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
### example of crosstabs
xtab( ~ N + P, npk)

Utility function to match 2 indices

Description

Function %xyb% or xyboth(x, y) shows index present in x, y and both

Usage

x %xyb% y
xyboth(x, y)

Arguments

x

vector(matrix/dataframe) of indices

y

vector(matrix/dataframe) of indices

Value

Returns a list with indices present only in x and y and in both.

Author(s)

Charles-Édouard Giguère

Examples

require(CUFF)
xyboth(1:5, 3:6)
### $x
### [1] "1" "2"
### 
### $y
### [1] "6"
### 
### $both
### [1] "3" "4" "5"