| Title: | Companion to "Learning Statistics with R" |
|---|---|
| Description: | A collection of tools intended to make introductory statistics easier to teach, including wrappers for common hypothesis tests and basic data manipulation. Accompanies the textbook "Learning Statistics with R: A Tutorial for Psychology Students and Other Beginners" by Navarro. |
| Authors: | Danielle Navarro [aut, cre] (ORCID: <https://orcid.org/0000-0001-7648-6578>) |
| Maintainer: | Danielle Navarro <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0 |
| Built: | 2026-07-11 18:36:02 UTC |
| Source: | https://github.com/djnavarro/lsr |
Calculates the mean absolute deviation from the sample mean.
aad(x, na.rm = FALSE)aad(x, na.rm = FALSE)
x |
A numeric vector containing the observations. |
na.rm |
Set to |
Computes the average of the absolute differences between each
observation and the sample mean of x, i.e.
mean(abs(x - mean(x))).
A single number giving the mean absolute deviation.
x <- c(1, 3, 6) aad(x) # missing values x <- c(1, 3, NA, 6) aad(x) # returns NA aad(x, na.rm = TRUE) # ignores the missing valuex <- c(1, 3, 6) aad(x) # missing values x <- c(1, 3, NA, 6) aad(x) # returns NA aad(x, na.rm = TRUE) # ignores the missing value
Runs a chi-square test to check whether two categorical variables are independent of one another.
associationTest(formula, data = NULL)associationTest(formula, data = NULL)
formula |
A one-sided formula of the form |
data |
An optional data frame containing the variables named in
|
The test checks whether two categorical variables are statistically
independent. Both variables must be factors, and the formula must be
one-sided with exactly two variables, e.g. ~gender + answer.
Missing values are removed before the test is run, and a warning is issued if any cases are dropped. When both variables have only two levels, Yates' continuity correction is applied automatically to the chi-squared statistic (though not to the Cramer's V effect size).
If either variable has unused factor levels (levels with zero observed
cases), a warning is issued. Those levels are included in the contingency
table with zero observed cases, which may give misleading results. Call
droplevels on the data first if this is not intended.
Prints a summary of the test showing the variable names, null and alternative hypotheses, observed and expected frequency tables, test results (chi-square statistic, degrees of freedom, p-value), and Cramer's V as a measure of effect size. The underlying results are also returned as a list, so the output can be assigned to a variable and inspected if needed.
chisq.test,
goodnessOfFitTest,
cramersV
df <- data.frame( gender = factor(c("male", "male", "male", "male", "female", "female", "female")), answer = factor(c("heads", "heads", "heads", "heads", "tails", "tails", "heads")) ) associationTest(~ gender + answer, df)df <- data.frame( gender = factor(c("male", "male", "male", "male", "female", "female", "female")), answer = factor(c("heads", "heads", "heads", "heads", "tails", "tails", "heads")) ) associationTest(~ gender + answer, df)
Creates a bar plot showing group means with error bars showing confidence intervals, broken down by one or two grouping factors.
bars( formula, data = NULL, heightFun = mean, errorFun = ciMean, yLabel = NULL, xLabels = NULL, main = "", ylim = NULL, barFillColour = NULL, barLineWidth = 2, barLineColour = "black", barSpaceSmall = 0.2, barSpaceBig = 1, legendLabels = NULL, legendDownShift = 0, legendLeftShift = 0, errorBarLineWidth = 1, errorBarLineColour = "grey40", errorBarWhiskerWidth = 0.2 )bars( formula, data = NULL, heightFun = mean, errorFun = ciMean, yLabel = NULL, xLabels = NULL, main = "", ylim = NULL, barFillColour = NULL, barLineWidth = 2, barLineColour = "black", barSpaceSmall = 0.2, barSpaceBig = 1, legendLabels = NULL, legendDownShift = 0, legendLeftShift = 0, errorBarLineWidth = 1, errorBarLineColour = "grey40", errorBarWhiskerWidth = 0.2 )
formula |
A two-sided formula of the form
|
data |
An optional data frame containing the variables named in
|
heightFun |
The function used to calculate bar heights. Defaults to
|
errorFun |
The function used to calculate error bar positions. Defaults
to |
yLabel |
The y-axis label. Defaults to the name of the response variable. |
xLabels |
Labels for the x-axis tick marks. Defaults to the levels of
|
main |
The plot title. Defaults to no title. |
ylim |
A numeric vector of length 2 giving the y-axis limits. The lower bound defaults to 0; the upper bound is estimated automatically. |
barFillColour |
A vector of colours used to fill the bars. Defaults to a pastel rainbow palette. |
barLineWidth |
The width of the bar border lines. Defaults to |
barLineColour |
The colour of the bar border lines. Defaults to
|
barSpaceSmall |
The gap between bars within a cluster, as a proportion
of bar width. Defaults to |
barSpaceBig |
The gap separating clusters of bars, as a proportion of
bar width. Defaults to |
legendLabels |
Labels for the legend entries. Defaults to the levels of
|
legendDownShift |
How far below the top of the plot to place the
legend, as a proportion of plot height. Defaults to |
legendLeftShift |
How far from the right edge to place the legend, as
a proportion of plot width. Defaults to |
errorBarLineWidth |
The line width for the error bars. Defaults to
|
errorBarLineColour |
The colour of the error bars. Defaults to
|
errorBarWhiskerWidth |
The width of the error bar whiskers, as a
proportion of bar width. Defaults to |
Plots group means (or the output of heightFun) with error
bars (or the output of errorFun) for one or two grouping factors.
When two grouping factors are given, group1 determines the primary
x-axis grouping and group2 determines the sub-grouping shown as
clusters of bars with a legend.
Missing values are removed with a warning. At least 2 complete cases are required per group.
Invisibly returns a data frame containing the factor levels, group summary values, and error bar bounds. This function is primarily used for its side effect of drawing the plot.
# one grouping factor df <- data.frame( outcome = c(3, 4, 5, 2, 4, 6, 5, 7, 8), group = factor(c("a", "a", "a", "b", "b", "b", "c", "c", "c")) ) bars(outcome ~ group, data = df) # two grouping factors df2 <- data.frame( outcome = c(3, 4, 5, 2, 4, 6, 5, 7, 8, 4, 3, 6), group1 = factor(rep(c("a", "b"), each = 6)), group2 = factor(rep(c("x", "y", "z"), times = 4)) ) bars(outcome ~ group1 + group2, data = df2)# one grouping factor df <- data.frame( outcome = c(3, 4, 5, 2, 4, 6, 5, 7, 8), group = factor(c("a", "a", "a", "b", "b", "b", "c", "c", "c")) ) bars(outcome ~ group, data = df) # two grouping factors df2 <- data.frame( outcome = c(3, 4, 5, 2, 4, 6, 5, 7, 8, 4, 3, 6), group1 = factor(rep(c("a", "b"), each = 6)), group2 = factor(rep(c("x", "y", "z"), times = 4)) ) bars(outcome ~ group1 + group2, data = df2)
Calculates a confidence interval for the mean of a numeric variable (or each numeric variable in a data frame or matrix).
ciMean(x, conf = 0.95, na.rm = FALSE)ciMean(x, conf = 0.95, na.rm = FALSE)
x |
A numeric vector, matrix, or data frame. |
conf |
The confidence level. Defaults to |
na.rm |
Set to |
Calculates a confidence interval for the mean under the standard
assumption that the data are normally distributed. When x is a
matrix or data frame, a separate interval is computed for each column.
Non-numeric columns in a data frame produce NA rows in the output.
A matrix with one row per variable and two columns giving the lower
and upper bounds of the confidence interval. Column names reflect the
confidence level (e.g., "2.5%" and "97.5%" for a 95%
interval).
x <- c(1, 3, 6) ciMean(x) # 95% confidence interval ciMean(x, conf = 0.80) # 80% confidence interval # for comparison: equivalent result via lm confint(lm(x ~ 1)) # missing values x <- c(1, 3, NA, 6) ciMean(x, na.rm = TRUE)x <- c(1, 3, 6) ciMean(x) # 95% confidence interval ciMean(x, conf = 0.80) # 80% confidence interval # for comparison: equivalent result via lm confint(lm(x ~ 1)) # missing values x <- c(1, 3, NA, 6) ciMean(x, na.rm = TRUE)
Calculates the Cohen's d measure of effect size.
cohensD( x = NULL, y = NULL, data = NULL, method = "pooled", mu = 0, formula = NULL )cohensD( x = NULL, y = NULL, data = NULL, method = "pooled", mu = 0, formula = NULL )
x |
A numeric vector of data for group 1, or a formula of the form
|
y |
A numeric vector of data for group 2. Omit for a one-sample calculation. |
data |
An optional data frame containing the variables in |
method |
Which version of Cohen's d to calculate. Options are
|
mu |
The null value for a one-sample calculation. Almost always 0 (the default). |
formula |
A formula of the form |
The function can be used in two main ways. For two separate
numeric vectors, call cohensD(x = group1, y = group2). For data in
a data frame with a grouping variable, use a formula:
cohensD(outcome ~ group, data = mydata).
The method argument controls how the standard deviation is estimated:
"pooled"Pooled SD from both groups (matches Student's t-test). This is the default.
"corrected"Bias-corrected version of "pooled",
multiplied by (N-3)/(N-2.25).
"raw"Like "pooled" but divides by N rather than
N-2.
"x.sd"SD of the first group only.
"y.sd"SD of the second group only.
"unequal"Square root of the average of the two group variances (matches Welch's t-test).
"paired"SD of the within-person differences (matches a paired-samples t-test).
For a one-sample calculation, supply only x (and optionally
mu). The result is abs(mean(x) - mu) / sd(x).
A single positive number: the magnitude of the effect size d. The sign of the mean difference is dropped, so the value is always zero or greater.
Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale, NJ: Lawrence Erlbaum Associates.
# two independent groups supplied as separate vectors gradesA <- c(55, 65, 65, 68, 70) # 5 students with teacher A gradesB <- c(56, 60, 62, 66) # 4 students with teacher B cohensD(gradesA, gradesB) # the same comparison using a formula and a data frame grade <- c(55, 65, 65, 68, 70, 56, 60, 62, 66) teacher <- c("A", "A", "A", "A", "A", "B", "B", "B", "B") cohensD(grade ~ teacher) # paired samples: use method = "paired" (SD of within-person differences) pre <- c(100, 122, 97, 25, 274) post <- c(104, 125, 99, 29, 277) cohensD(pre, post, method = "paired") # equivalent one-sample calculation on the difference scores cohensD(post - pre) # formula interface with a data frame exams <- data.frame(grade, teacher) cohensD(grade ~ teacher, data = exams)# two independent groups supplied as separate vectors gradesA <- c(55, 65, 65, 68, 70) # 5 students with teacher A gradesB <- c(56, 60, 62, 66) # 4 students with teacher B cohensD(gradesA, gradesB) # the same comparison using a formula and a data frame grade <- c(55, 65, 65, 68, 70, 56, 60, 62, 66) teacher <- c("A", "A", "A", "A", "A", "B", "B", "B", "B") cohensD(grade ~ teacher) # paired samples: use method = "paired" (SD of within-person differences) pre <- c(100, 122, 97, 25, 274) post <- c(104, 125, 99, 29, 277) cohensD(pre, post, method = "paired") # equivalent one-sample calculation on the difference scores cohensD(post - pre) # formula interface with a data frame exams <- data.frame(grade, teacher) cohensD(grade ~ teacher, data = exams)
Creates a matrix by stacking multiple copies of a vector as
rows (rowCopy) or as columns (colCopy).
colCopy(x, times, dimnames = NULL) rowCopy(x, times, dimnames = NULL)colCopy(x, times, dimnames = NULL) rowCopy(x, times, dimnames = NULL)
x |
A vector to be copied. |
times |
The number of copies to stack together. |
dimnames |
An optional list specifying row and column names for the output matrix. |
These functions are shortcuts for building a matrix where every
row (or every column) is the same vector. They are equivalent to calling
matrix with appropriate byrow and dimension arguments.
For rowCopy, a matrix with times rows and
length(x) columns, where each row is x. For colCopy,
a matrix with length(x) rows and times columns, where each
column is x.
x <- c(3, 1, 4, 1, 5) # stack x as rows rowCopy(x, 4) # stack x as columns colCopy(x, 4) # with custom dimension names dnames <- list(rows = c("r1", "r2", "r3"), cols = c("c1", "c2", "c3", "c4", "c5")) rowCopy(x, 3, dnames)x <- c(3, 1, 4, 1, 5) # stack x as rows rowCopy(x, 4) # stack x as columns colCopy(x, 4) # with custom dimension names dnames <- list(rows = c("r1", "r2", "r3"), cols = c("c1", "c2", "c3", "c4", "c5")) rowCopy(x, 3, dnames)
Computes a correlation matrix, optionally with hypothesis tests and corrections for multiple comparisons.
correlate( x, y = NULL, test = FALSE, corr.method = "pearson", p.adjust.method = "holm" )correlate( x, y = NULL, test = FALSE, corr.method = "pearson", p.adjust.method = "holm" )
x |
A numeric vector, matrix, or data frame containing the variables to be correlated. |
y |
An optional second matrix or data frame. If provided, the variables
in |
test |
Set to |
corr.method |
The type of correlation to compute: |
p.adjust.method |
The method used to correct p-values for multiple
comparisons. Defaults to |
Calculates a correlation matrix between all pairs of numeric
variables. If only x is supplied, all pairwise correlations among
the variables in x are computed. If both x and y are
supplied, variables in x are correlated with variables in y.
Non-numeric variables (e.g., factors) are silently ignored: they appear in
the output with NA in place of correlation values. This makes it
convenient to pass an entire data frame without first removing categorical
columns.
When test = TRUE, hypothesis tests are run for every pair of numeric
variables. To reduce the risk of false positives from testing many pairs at
once, p-values are adjusted using the Holm method by default. See
p.adjust for other available methods.
Missing data are handled using pairwise complete cases, so sample sizes may
differ across pairs of variables. If a particular pair of variables has too
few complete observations for cor.test to run, the
corresponding cell in the correlation matrix is left as NA rather
than causing the whole call to fail.
Prints the correlation matrix. If test = TRUE, also prints a
matrix of adjusted p-values and a matrix of sample sizes. The results are
also returned as a list with four elements: correlation (the
correlation matrix), p.value (the matrix of p-values),
sample.size (the matrix of sample sizes), and args (a record
of the options used). The list can be assigned to a variable and inspected
if needed.
# data frame with factors and missing values data <- data.frame( anxiety = c(1.31, 2.72, 3.18, 4.21, 5.55, NA), stress = c(2.01, 3.45, 1.99, 3.25, 4.27, 6.80), depression = c(2.51, 1.77, 3.34, 5.83, 9.01, 7.74), happiness = c(4.02, 3.66, 5.23, 6.37, 7.83, 1.18), gender = factor(c("male", "female", "female", "male", "female", "female")), ssri = factor(c("no", "no", "no", NA, "yes", "yes")) ) # Pearson correlation matrix (the default) correlate(data) # Spearman correlations correlate(data, corr.method = "spearman") # correlate two subsets of variables with each other nervous <- data[, c("anxiety", "stress")] happy <- data[, c("happiness", "depression")] correlate(nervous, happy) # include Holm-corrected p-values and sample sizes correlate(data, test = TRUE)# data frame with factors and missing values data <- data.frame( anxiety = c(1.31, 2.72, 3.18, 4.21, 5.55, NA), stress = c(2.01, 3.45, 1.99, 3.25, 4.27, 6.80), depression = c(2.51, 1.77, 3.34, 5.83, 9.01, 7.74), happiness = c(4.02, 3.66, 5.23, 6.37, 7.83, 1.18), gender = factor(c("male", "female", "female", "male", "female", "female")), ssri = factor(c("no", "no", "no", NA, "yes", "yes")) ) # Pearson correlation matrix (the default) correlate(data) # Spearman correlations correlate(data, corr.method = "spearman") # correlate two subsets of variables with each other nervous <- data[, c("anxiety", "stress")] happy <- data[, c("happiness", "depression")] correlate(nervous, happy) # include Holm-corrected p-values and sample sizes correlate(data, test = TRUE)
Calculates Cramer's V, a measure of the strength of association for chi-square tests.
cramersV(...)cramersV(...)
... |
Arguments passed to |
Cramer's V summarises the strength of association from a chi-square test. It is appropriate for both tests of association (two categorical variables) and goodness of fit tests (one variable versus hypothesised probabilities). Values range from 0 (no association) to 1 (perfect association).
Yates' continuity correction is never applied, regardless of the table dimensions. This is intentional: applying the correction reduces the chi-squared statistic, which causes V to fall below 1 even for perfectly associated 2x2 tables — inconsistent with its definition as an effect size on the [0, 1] scale.
A single number giving the value of Cramer's V.
chisq.test,
associationTest,
goodnessOfFitTest
# frequency table for two groups, each choosing from three options condition1 <- c(30, 20, 50) condition2 <- c(35, 30, 35) X <- cbind(condition1, condition2) rownames(X) <- c("choice1", "choice2", "choice3") # chi-square test of association chisq.test(X) # effect size estimate cramersV(X)# frequency table for two groups, each choosing from three options condition1 <- c(30, 20, 50) condition2 <- c(35, 30, 35) X <- cbind(condition1, condition2) rownames(X) <- c("choice1", "choice2", "choice3") # chi-square test of association chisq.test(X) # effect size estimate cramersV(X)
Calculates eta-squared and partial eta-squared effect sizes for an analysis of variance.
etaSquared(x, type = 2, anova = FALSE)etaSquared(x, type = 2, anova = FALSE)
x |
An |
type |
Which type of sums of squares to use: |
anova |
Set to |
Calculates eta-squared and partial eta-squared, two commonly used
measures of effect size in analysis of variance. The input x should
be an ANOVA fitted with aov.
For unbalanced designs, Type II sums of squares (type = 2) are
recommended and are the default, consistent with the Anova function
in the car package. Type I (type = 1) matches the output of
anova but tests hypotheses that are often not of interest in
unbalanced designs. Type III (type = 3) is also available.
A matrix with one row per term in the ANOVA model and columns for
eta-squared (eta.sq) and partial eta-squared (eta.sq.part).
If anova = TRUE, additional columns show the sums of squares,
mean squares, degrees of freedom, F-statistics, and p-values.
outcome <- c(1.4, 2.1, 3.0, 2.1, 3.2, 4.7, 3.5, 4.5, 5.4) treatment1 <- factor(c(1, 1, 1, 2, 2, 2, 3, 3, 3)) # one-way ANOVA anova1 <- aov(outcome ~ treatment1) summary(anova1) etaSquared(anova1) # include the full ANOVA table etaSquared(anova1, anova = TRUE) # two-way ANOVA treatment2 <- factor(c(1, 2, 3, 1, 2, 3, 1, 2, 3)) anova2 <- aov(outcome ~ treatment1 + treatment2) etaSquared(anova2)outcome <- c(1.4, 2.1, 3.0, 2.1, 3.2, 4.7, 3.5, 4.5, 5.4) treatment1 <- factor(c(1, 1, 1, 2, 2, 2, 3, 3, 3)) # one-way ANOVA anova1 <- aov(outcome ~ treatment1) summary(anova1) etaSquared(anova1) # include the full ANOVA table etaSquared(anova1, anova = TRUE) # two-way ANOVA treatment2 <- factor(c(1, 2, 3, 1, 2, 3, 1, 2, 3)) anova2 <- aov(outcome ~ treatment1 + treatment2) etaSquared(anova2)
Replaces each factor variable in a data frame with its contrast-coded columns, leaving numeric variables unchanged.
expandFactors(data, ...)expandFactors(data, ...)
data |
A data frame. |
... |
Additional arguments passed to |
Each factor in data is replaced by the numeric contrast
columns that model.matrix would generate for that factor
(using treatment contrasts by default). Numeric variables pass through
unchanged. This can be helpful when illustrating the connection between
ANOVA and regression.
A data frame with factor columns replaced by numeric contrast columns.
grading <- data.frame( teacher = factor(c("Amy", "Amy", "Ben", "Ben", "Cat")), gender = factor(c("male", "female", "female", "male", "male")), grade = c(75, 80, 45, 50, 65) ) # expand using the default contrasts (treatment contrasts) expandFactors(grading) # specify different contrasts via contrasts.arg my.contrasts <- list(teacher = "contr.helmert", gender = "contr.treatment") expandFactors(grading, contrasts.arg = my.contrasts)grading <- data.frame( teacher = factor(c("Amy", "Amy", "Ben", "Ben", "Cat")), gender = factor(c("male", "female", "female", "male", "male")), grade = c(75, 80, 45, 50, 65) ) # expand using the default contrasts (treatment contrasts) expandFactors(grading) # specify different contrasts via contrasts.arg my.contrasts <- list(teacher = "contr.helmert", gender = "contr.treatment") expandFactors(grading, contrasts.arg = my.contrasts)
Runs a chi-square goodness of fit test to check whether the observed frequencies in a categorical variable match a set of hypothesised probabilities.
goodnessOfFitTest(x, p = NULL)goodnessOfFitTest(x, p = NULL)
x |
A factor variable containing the observed outcomes. |
p |
A numeric vector of hypothesised probabilities, one per level of
|
The test checks whether the observed frequencies for a categorical
variable are consistent with the probabilities specified in p.
Missing values in x are removed before the test is run, and a
warning is issued if any cases are dropped. If the probabilities in
p do not sum exactly to 1, they are rescaled with a warning.
If x has unused factor levels (levels with zero observed cases), a
warning is issued. Those levels are included in the test with zero observed
cases, which changes the degrees of freedom and may give misleading results.
Call droplevels on the data first if this is not intended.
Prints a summary of the test showing the variable name, null and alternative hypotheses, a table of observed frequencies, expected frequencies, and hypothesised probabilities, and the test results (chi-square statistic, degrees of freedom, p-value). The underlying results are also returned as a list, so the output can be assigned to a variable and inspected if needed.
chisq.test,
associationTest,
cramersV
# raw data gender <- factor( c( "male", "male", "male", "male", "female", "female", "female", "male", "male", "male" ) ) # goodness of fit test against the hypothesis that males and # females occur with equal frequency goodnessOfFitTest(gender) # goodness of fit test against the hypothesis that males appear # with probability .6 and females with probability .4. goodnessOfFitTest(gender, p = c(.4, .6)) goodnessOfFitTest(gender, p = c(female = .4, male = .6)) goodnessOfFitTest(gender, p = c(male = .6, female = .4))# raw data gender <- factor( c( "male", "male", "male", "male", "female", "female", "female", "male", "male", "male" ) ) # goodness of fit test against the hypothesis that males and # females occur with equal frequency goodnessOfFitTest(gender) # goodness of fit test against the hypothesis that males appear # with probability .6 and females with probability .4. goodnessOfFitTest(gender, p = c(.4, .6)) goodnessOfFitTest(gender, p = c(female = .4, male = .6)) goodnessOfFitTest(gender, p = c(male = .6, female = .4))
Copies each element of a list into a separate variable in the workspace, using the list element names as variable names.
importList(x, ask = TRUE)importList(x, ask = TRUE)
x |
A list or data frame whose elements are to be imported as individual variables. |
ask |
Set to |
Creates one variable per list element in the calling environment
(usually the global workspace). All elements of x must be named;
passing an unnamed or partially-named list is an error. Element names that
are not valid R variable names are automatically converted using
make.names. An empty list produces a message and returns
invisibly without creating any variables.
Called primarily for its side effect of creating variables in the
workspace. Invisibly returns 1 if variables were created, 0
if the user declined.
values <- c(1, 2, 3, 4, 5) group <- c("group A", "group A", "group B", "group B", "group B") # split() returns a named list: one element per group grp_list <- split(values, group) # import silently (no confirmation prompt) importList(grp_list, ask = FALSE) if (FALSE) { # interactive: shows variable names and asks for confirmation importList(grp_list) }values <- c(1, 2, 3, 4, 5) group <- c("group A", "group A", "group B", "group B", "group B") # split() returns a named list: one element per group grp_list <- split(values, group) # import silently (no confirmation prompt) importList(grp_list, ask = FALSE) if (FALSE) { # interactive: shows variable names and asks for confirmation importList(grp_list) }
Runs an independent-samples t-test and prints the results in a readable format.
independentSamplesTTest( formula, data = NULL, var.equal = FALSE, one.sided = FALSE, conf.level = 0.95 )independentSamplesTTest( formula, data = NULL, var.equal = FALSE, one.sided = FALSE, conf.level = 0.95 )
formula |
A formula of the form |
data |
An optional data frame containing the variables named in
|
var.equal |
Set to |
one.sided |
Set to |
conf.level |
The confidence level for the confidence interval.
The default is |
Runs an independent-samples t-test comparing the means of two
groups, and prints the results in a beginner-friendly format. The
calculations are done by t.test and cohensD.
When var.equal = TRUE, Cohen's d uses a pooled standard deviation;
when var.equal = FALSE (Welch's test), it uses the "unequal" method.
Cases with missing values are removed with a warning.
Prints a summary showing the outcome and grouping variable names, group means and standard deviations, null and alternative hypotheses, test results (t-statistic, degrees of freedom, p-value), a confidence interval, and Cohen's d as a measure of effect size. The underlying results are also returned as a list, so the output can be assigned to a variable and inspected if needed.
t.test,
oneSampleTTest,
pairedSamplesTTest,
cohensD
df <- data.frame( rt = c(451, 562, 704, 324, 505, 600, 829), cond = factor(x = c(1, 1, 1, 2, 2, 2, 2), labels = c("group1", "group2")) ) # Welch's t-test (the default, does not assume equal variances) independentSamplesTTest(rt ~ cond, df) # Student's t-test (assumes equal variances) independentSamplesTTest(rt ~ cond, df, var.equal = TRUE) # one-sided test: is group1 larger? independentSamplesTTest(rt ~ cond, df, one.sided = "group1") # missing values are removed with a warning df$rt[1] <- NA df$cond[7] <- NA independentSamplesTTest(rt ~ cond, df)df <- data.frame( rt = c(451, 562, 704, 324, 505, 600, 829), cond = factor(x = c(1, 1, 1, 2, 2, 2, 2), labels = c("group1", "group2")) ) # Welch's t-test (the default, does not assume equal variances) independentSamplesTTest(rt ~ cond, df) # Student's t-test (assumes equal variances) independentSamplesTTest(rt ~ cond, df, var.equal = TRUE) # one-sided test: is group1 larger? independentSamplesTTest(rt ~ cond, df, one.sided = "group1") # missing values are removed with a warning df$rt[1] <- NA df$cond[7] <- NA independentSamplesTTest(rt ~ cond, df)
Reshapes a data frame from long form (one row per observation) to wide form (one row per subject), using a formula to specify the structure.
longToWide(data, formula, sep = "_")longToWide(data, formula, sep = "_")
data |
A long-form data frame with one row per observation. |
formula |
A two-sided formula of the form |
sep |
The separator string used to construct wide-form variable names.
Defaults to |
This function is the companion to wideToLong. It
reshapes a long-form data frame into wide form by spreading the within-subject
observations across columns, with column names constructed from the measure
name and factor level(s) joined by sep.
A wide-form data frame with one row per subject (or experimental
unit). Column names for the repeated measures follow the naming convention
used by wideToLong: the measure name followed by the
within-subject factor level(s), separated by sep.
long <- data.frame( id = c(1, 2, 3, 1, 2, 3, 1, 2, 3), time = c("t1", "t1", "t1", "t2", "t2", "t2", "t3", "t3", "t3"), accuracy = c(.50, .03, .72, .94, .63, .49, .78, .71, .16) ) longToWide(long, accuracy ~ time)long <- data.frame( id = c(1, 2, 3, 1, 2, 3, 1, 2, 3), time = c("t1", "t1", "t1", "t2", "t2", "t2", "t3", "t3", "t3"), accuracy = c(.50, .03, .72, .94, .63, .49, .78, .71, .16) ) longToWide(long, accuracy ~ time)
Calculate the most frequently occurring value(s) in a sample
(modeOf) or the frequency of the most common value (maxFreq).
modeOf(x, na.rm = TRUE) maxFreq(x, na.rm = TRUE)modeOf(x, na.rm = TRUE) maxFreq(x, na.rm = TRUE)
x |
A vector or factor containing the observations. |
na.rm |
Set to |
When na.rm = FALSE, missing values are treated as a
distinct value that can itself be the mode. If the number of NAs
exceeds the frequency of every other value, modeOf returns
NA and maxFreq returns the count of missing values.
Because of this ambiguity, the default is na.rm = TRUE, unlike
most other functions in this package.
modeOf returns the most frequently observed value. If
multiple values are tied for the highest frequency, all of them are
returned as a vector. If the input has no non-missing values, modeOf
issues a warning and returns NA. maxFreq returns the modal
frequency as a single number, or NA with a warning if the input has
no non-missing values.
eyes <- c("green", "green", "brown", "brown", "blue") modeOf(eyes) # returns c("green", "brown") -- a tie maxFreq(eyes) # returns 2 # with missing data eyes <- c("green", "green", "brown", "brown", "blue", NA, NA, NA) # na.rm = FALSE: NA is the most frequent "value" modeOf(eyes, na.rm = FALSE) maxFreq(eyes, na.rm = FALSE) # na.rm = TRUE: missing values ignored modeOf(eyes, na.rm = TRUE) maxFreq(eyes, na.rm = TRUE) NULLeyes <- c("green", "green", "brown", "brown", "blue") modeOf(eyes) # returns c("green", "brown") -- a tie maxFreq(eyes) # returns 2 # with missing data eyes <- c("green", "green", "brown", "brown", "blue", NA, NA, NA) # na.rm = FALSE: NA is the most frequent "value" modeOf(eyes, na.rm = FALSE) maxFreq(eyes, na.rm = FALSE) # na.rm = TRUE: missing values ignored modeOf(eyes, na.rm = TRUE) maxFreq(eyes, na.rm = TRUE) NULL
Runs a one-sample t-test and prints the results in a readable format.
oneSampleTTest(x, mu, one.sided = FALSE, conf.level = 0.95)oneSampleTTest(x, mu, one.sided = FALSE, conf.level = 0.95)
x |
A numeric vector containing the data to be tested. |
mu |
The hypothesised population mean to test against. |
one.sided |
Set to |
conf.level |
The confidence level for the confidence interval.
The default is |
Runs a one-sample t-test comparing the mean of x to the
hypothesised value mu, and prints the results in a beginner-friendly
format. The calculations are done by t.test and
cohensD. Missing values in x are removed with a
warning.
Prints a summary showing the variable name, descriptive statistics, null and alternative hypotheses, test results (t-statistic, degrees of freedom, p-value), a confidence interval, and Cohen's d as a measure of effect size. The underlying results are also returned as a list, so the output can be assigned to a variable and inspected if needed.
t.test,
pairedSamplesTTest,
independentSamplesTTest,
cohensD
likert <- c(3, 1, 4, 1, 4, 6, 7, 2, 6, 6, 7) # two-sided test (the default) oneSampleTTest(x = likert, mu = 4) # one-sided test: is the mean greater than 4? oneSampleTTest(x = likert, mu = 4, one.sided = "greater") # wider confidence interval oneSampleTTest(x = likert, mu = 4, conf.level = 0.99) # missing values are removed with a warning likert <- c(3, NA, 4, NA, 4, 6, 7, NA, 6, 6, 7) oneSampleTTest(x = likert, mu = 4)likert <- c(3, 1, 4, 1, 4, 6, 7, 2, 6, 6, 7) # two-sided test (the default) oneSampleTTest(x = likert, mu = 4) # one-sided test: is the mean greater than 4? oneSampleTTest(x = likert, mu = 4, one.sided = "greater") # wider confidence interval oneSampleTTest(x = likert, mu = 4, conf.level = 0.99) # missing values are removed with a warning likert <- c(3, NA, 4, NA, 4, 6, 7, NA, 6, 6, 7) oneSampleTTest(x = likert, mu = 4)
Runs a paired-samples t-test and prints the results in a readable format.
pairedSamplesTTest( formula, data = NULL, id = NULL, one.sided = FALSE, conf.level = 0.95 )pairedSamplesTTest( formula, data = NULL, id = NULL, one.sided = FALSE, conf.level = 0.95 )
formula |
A formula describing the data. For wide-format data use a
one-sided formula such as |
data |
An optional data frame containing the variables named in
|
id |
The name of the participant ID variable as a character string
(e.g., |
one.sided |
Set to |
conf.level |
The confidence level for the confidence interval.
The default is |
Runs a paired-samples t-test and prints the results in a
beginner-friendly format. The calculations are done by t.test
and cohensD.
There are two ways to supply data. If the data are in wide format
(one row per participant, with the two measurements in separate columns),
use a one-sided formula such as ~ time1 + time2. The first row of
time1 is paired with the first row of time2, and so on.
If the data are in long format (two rows per participant), use a
two-sided formula. The recommended style is outcome ~ group + (id),
where the participant ID variable is enclosed in parentheses. Alternatively,
use the plain formula outcome ~ group and supply the ID variable name
via the id argument. The lme4-style notation
outcome ~ group + (1|id) is also accepted as equivalent to
outcome ~ group + (id).
Participants with missing measurements are removed with a warning.
Prints a summary showing the variable names, descriptive statistics (including the mean and standard deviation of the differences), null and alternative hypotheses, test results (t-statistic, degrees of freedom, p-value), a confidence interval, and Cohen's d as a measure of effect size. The underlying results are also returned as a list, so the output can be assigned to a variable and inspected if needed.
t.test,
oneSampleTTest,
independentSamplesTTest,
cohensD
# long-format data: one row per participant per time point df <- data.frame( id = factor( x = c(1, 1, 2, 2, 3, 3, 4, 4), labels = c("alice", "bob", "chris", "diana") ), time = factor( x = c(1, 2, 1, 2, 1, 2, 1, 2), labels = c("time1", "time2") ), wm = c(3, 4, 6, 6, 9, 12, 7, 9) ) # wide-format data: one row per participant df2 <- longToWide(df, wm ~ time) # three equivalent ways to run the same test pairedSamplesTTest(formula = wm ~ time, data = df, id = "id") pairedSamplesTTest(formula = wm ~ time + (id), data = df) pairedSamplesTTest(formula = ~ wm_time1 + wm_time2, data = df2) # one-sided test: is time2 larger than time1? pairedSamplesTTest(formula = wm ~ time, data = df, id = "id", one.sided = "time2") # missing value: that participant is removed with a warning df$wm[1] <- NA pairedSamplesTTest(formula = wm ~ time, data = df, id = "id") # missing row: that participant is also removed with a warning df <- df[-1, ] pairedSamplesTTest(formula = wm ~ time, data = df, id = "id")# long-format data: one row per participant per time point df <- data.frame( id = factor( x = c(1, 1, 2, 2, 3, 3, 4, 4), labels = c("alice", "bob", "chris", "diana") ), time = factor( x = c(1, 2, 1, 2, 1, 2, 1, 2), labels = c("time1", "time2") ), wm = c(3, 4, 6, 6, 9, 12, 7, 9) ) # wide-format data: one row per participant df2 <- longToWide(df, wm ~ time) # three equivalent ways to run the same test pairedSamplesTTest(formula = wm ~ time, data = df, id = "id") pairedSamplesTTest(formula = wm ~ time + (id), data = df) pairedSamplesTTest(formula = ~ wm_time1 + wm_time2, data = df2) # one-sided test: is time2 larger than time1? pairedSamplesTTest(formula = wm ~ time, data = df, id = "id", one.sided = "time2") # missing value: that participant is removed with a warning df$wm[1] <- NA pairedSamplesTTest(formula = wm ~ time, data = df, id = "id") # missing row: that participant is also removed with a warning df <- df[-1, ] pairedSamplesTTest(formula = wm ~ time, data = df, id = "id")
Reorder the levels of a factor into any order you specify.
permuteLevels(x, perm, ordered = is.ordered(x), invert = FALSE)permuteLevels(x, perm, ordered = is.ordered(x), invert = FALSE)
x |
A factor. |
perm |
An integer vector of the same length as |
ordered |
Set to |
invert |
Set to |
Similar to relevel, but more general:
relevel can only move one level to the front, whereas
permuteLevels can place the levels in any order. This is useful
when you want to control the order in which levels appear on a plot axis
or in a table.
A factor with the same values as x but with the levels
in the new order specified by perm.
# factor with levels a, b, c, d, e, f (in that order) x <- factor(c(1, 4, 2, 2, 3, 3, 5, 5, 6, 6), labels = letters[1:6]) levels(x) # move level e to position 1, c to position 2, b to 3, a to 4, d to 5, f to 6 permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6)) # using invert = TRUE: move level a to position 5, b to 3, c to 2, etc. permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6), invert = TRUE)# factor with levels a, b, c, d, e, f (in that order) x <- factor(c(1, 4, 2, 2, 3, 3, 5, 5, 6, 6), labels = letters[1:6]) levels(x) # move level e to position 1, c to position 2, b to 3, a to 4, d to 5, f to 6 permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6)) # using invert = TRUE: move level a to position 5, b to 3, c to 2, etc. permuteLevels(x, perm = c(5, 3, 2, 1, 4, 6), invert = TRUE)
Runs pairwise t-tests for a one-way analysis of variance, with corrections for multiple comparisons.
posthocPairwiseT(x, ...)posthocPairwiseT(x, ...)
x |
An |
... |
Additional arguments passed to |
Takes a fitted one-way ANOVA object and runs pairwise t-tests for
all pairs of groups, applying a correction for multiple comparisons. This
is a simpler alternative to TukeyHSD that uses the same
correction methods (e.g., Holm, Bonferroni) as
pairwise.t.test.
Prints a table of p-values for all pairwise group comparisons. The
underlying result is also returned as a list (with the same structure as
pairwise.t.test) so it can be assigned to a variable and
inspected if needed.
pairwise.t.test,
TukeyHSD,
aov
dataset <- data.frame( outcome = c(1, 2, 3, 2, 3, 4, 5, 6, 7), group = factor(c("a", "a", "a", "b", "b", "b", "c", "c", "c")) ) anova1 <- aov(outcome ~ group, data = dataset) summary(anova1) # post-hoc pairwise comparisons with Holm correction (the default) posthocPairwiseT(anova1) # Bonferroni correction instead posthocPairwiseT(anova1, p.adjust.method = "bonferroni")dataset <- data.frame( outcome = c(1, 2, 3, 2, 3, 4, 5, 6, 7), group = factor(c("a", "a", "a", "b", "b", "b", "c", "c", "c")) ) anova1 <- aov(outcome ~ group, data = dataset) summary(anova1) # post-hoc pairwise comparisons with Holm correction (the default) posthocPairwiseT(anova1) # Bonferroni correction instead posthocPairwiseT(anova1, p.adjust.method = "bonferroni")
Prints the results of a chi-square test of association in a
readable format. This function is called automatically whenever a result
from associationTest is displayed.
## S3 method for class 'assocTest' print(x, ...)## S3 method for class 'assocTest' print(x, ...)
x |
An association test result, as returned by
|
... |
Additional arguments (unused, included for compatibility). |
Invisibly returns x unchanged.
Prints the results of a correlation analysis in a readable
format. This function is called automatically whenever a result from
correlate is displayed.
## S3 method for class 'correlate' print(x, ...)## S3 method for class 'correlate' print(x, ...)
x |
A correlation result, as returned by |
... |
Additional arguments (unused, included for compatibility). |
Invisibly returns x unchanged.
Prints the results of a chi-square goodness of fit test in a
readable format. This function is called automatically whenever a result
from goodnessOfFitTest is displayed.
## S3 method for class 'gofTest' print(x, ...)## S3 method for class 'gofTest' print(x, ...)
x |
A goodness of fit test result, as returned by
|
... |
Additional arguments (unused, included for compatibility). |
Invisibly returns x unchanged.
Prints the results of a t-test in a readable, beginner-friendly
format. This function is called automatically whenever a result from
oneSampleTTest, independentSamplesTTest, or
pairedSamplesTTest is displayed.
## S3 method for class 'TTest' print(x, ...)## S3 method for class 'TTest' print(x, ...)
x |
A t-test result, as returned by |
... |
Additional arguments (unused, included for compatibility). |
Invisibly returns x unchanged.
Prints a workspace summary in a readable format. This function
is called automatically whenever a result from who is
displayed.
## S3 method for class 'whoList' print(x, ...)## S3 method for class 'whoList' print(x, ...)
x |
A workspace summary, as returned by |
... |
Additional arguments (unused, included for compatibility). |
Invisibly returns x unchanged.
Divides a numeric variable into n categories that each
contain approximately the same number of observations.
quantileCut(x, n, ...)quantileCut(x, n, ...)
x |
A numeric vector. |
n |
The number of categories to create. |
... |
Additional arguments passed to |
Unlike cut, which creates categories of equal width,
quantileCut uses quantile to find breakpoints that
produce roughly equal-sized groups. This can be useful in exploratory
analysis, but the resulting categories are data-driven and may not have
a clear interpretation. Using them as grouping variables in an ANOVA is
generally not recommended, as the breakpoints are arbitrary and the groups
will typically not have equal variances.
A factor with n levels. Level labels follow the same
convention as cut and can be overridden with the
labels argument.
# the data are unevenly spread, so equal-width bins would be unbalanced x <- c(0, 1, 2, 3, 4, 5, 7, 10, 15) # quantileCut creates equal-frequency bins bins_eq_freq <- quantileCut(x, 3) table(bins_eq_freq) # compare to cut(), which creates equal-width bins bins_eq_width <- cut(x, 3) table(bins_eq_width)# the data are unevenly spread, so equal-width bins would be unbalanced x <- c(0, 1, 2, 3, 4, 5, 7, 10, 15) # quantileCut creates equal-frequency bins bins_eq_freq <- quantileCut(x, 3) table(bins_eq_freq) # compare to cut(), which creates equal-width bins bins_eq_width <- cut(x, 3) table(bins_eq_width)
Deletes all objects from the workspace, with an optional confirmation prompt.
rmAll(ask = TRUE)rmAll(ask = TRUE)
ask |
Set to |
Removes all objects from the workspace. When ask = TRUE,
the list of objects is printed and the user must type y to confirm
before anything is deleted. This is similar to rm(list = objects()),
but with an interactive safety check.
Invisibly returns 1 if objects were deleted, 0 if
the user declined or the workspace was already empty.
if (FALSE) { # interactive: displays workspace contents and asks for confirmation rmAll() # non-interactive: deletes immediately without prompting rmAll(ask = FALSE) }if (FALSE) { # interactive: displays workspace contents and asks for confirmation rmAll() # non-interactive: deletes immediately without prompting rmAll(ask = FALSE) }
Sorts a data frame by one or more of its variables.
sortFrame(x, ..., alphabetical = TRUE)sortFrame(x, ..., alphabetical = TRUE)
x |
A data frame to be sorted. |
... |
One or more unquoted variable names to sort by, in order of
priority. Prefix a variable name with |
alphabetical |
Set to |
Sorts the rows of x by the variables listed in ....
Numeric variables and factors are sorted by their numeric values (for
factors, this corresponds to level order). Character variables are sorted
alphabetically by default, ignoring case; prefix with - for reverse
alphabetical order.
Simple expressions combining variables are also accepted (e.g.,
sortFrame(x, a + b) sorts by the sum of a and b),
though care is required: the sort uses xtfrm internally to
convert variables to sortable numeric codes, which can produce unexpected
results for character variables when expressions other than -
are used.
The sorted data frame.
dataset <- data.frame( txt = c("bob", "Clare", "clare", "bob", "eve", "eve"), num1 = c(3, 1, 2, 0, 0, 2), num2 = c(1, 1, 3, 0, 3, 2), stringsAsFactors = FALSE ) sortFrame(dataset, num1) # sort by num1 ascending sortFrame(dataset, num1, num2) # sort by num1 then num2 sortFrame(dataset, -num1) # sort by num1 descending sortFrame(dataset, txt) # sort alphabetically (case-insensitive)dataset <- data.frame( txt = c("bob", "Clare", "clare", "bob", "eve", "eve"), num1 = c(3, 1, 2, 0, 0, 2), num2 = c(1, 1, 3, 0, 3, 2), stringsAsFactors = FALSE ) sortFrame(dataset, num1) # sort by num1 ascending sortFrame(dataset, num1, num2) # sort by num1 then num2 sortFrame(dataset, -num1) # sort by num1 descending sortFrame(dataset, txt) # sort alphabetically (case-insensitive)
Calculates standardised regression coefficients (beta weights) for a linear model.
standardCoefs(x)standardCoefs(x)
x |
A linear model, as returned by |
Standardised coefficients are the regression coefficients that would result from fitting the model after scaling all predictors and the outcome to have mean 0 and variance 1. They can be useful for comparing the relative magnitude of predictors measured on different scales, though this comparison should be interpreted with care.
Note that when a model contains interaction terms, the interaction column is also standardised as a whole, rather than being constructed from standardised versions of the constituent predictors.
A matrix with one row per predictor (excluding the intercept) and
two columns: b (unstandardised coefficient) and beta
(standardised coefficient).
X1 <- c(0.69, 0.77, 0.92, 1.72, 1.79, 2.37, 2.64, 2.69, 2.84, 3.41) Y <- c(3.28, 4.23, 3.34, 3.73, 5.33, 6.02, 5.16, 6.49, 6.49, 6.05) # simple linear regression model1 <- lm(Y ~ X1) coefficients(model1) # unstandardised standardCoefs(model1) # unstandardised and standardised side by side # multiple regression X2 <- c(0.19, 0.22, 0.95, 0.43, 0.51, 0.04, 0.12, 0.44, 0.38, 0.33) model2 <- lm(Y ~ X1 + X2) standardCoefs(model2) # model with an interaction term model3 <- lm(Y ~ X1 * X2) standardCoefs(model3)X1 <- c(0.69, 0.77, 0.92, 1.72, 1.79, 2.37, 2.64, 2.69, 2.84, 3.41) Y <- c(3.28, 4.23, 3.34, 3.73, 5.33, 6.02, 5.16, 6.49, 6.49, 6.05) # simple linear regression model1 <- lm(Y ~ X1) coefficients(model1) # unstandardised standardCoefs(model1) # unstandardised and standardised side by side # multiple regression X2 <- c(0.19, 0.22, 0.95, 0.43, 0.51, 0.04, 0.12, 0.44, 0.38, 0.33) model2 <- lm(Y ~ X1 + X2) standardCoefs(model2) # model with an interaction term model3 <- lm(Y ~ X1 * X2) standardCoefs(model3)
Transposes a data frame, swapping rows and columns, and returns the result as a data frame.
tFrame(x)tFrame(x)
x |
A data frame to be transposed. |
Equivalent to as.data.frame(t(x)). Unlike applying
t directly, tFrame ensures the result is a data frame
rather than a matrix. This makes sense when the rows of x can be
meaningfully treated as variables — for example, when each row represents a
measurement type and each column represents a participant.
The transposed data frame.
dataset <- data.frame( Gf = c(105, 119, 121, 98), # fluid intelligence Gc = c(110, 115, 119, 103), # crystallised intelligence Gs = c(112, 102, 108, 99) # processing speed ) rownames(dataset) <- paste0("person", 1:4) dataset tFrame(dataset)dataset <- data.frame( Gf = c(105, 119, 121, 98), # fluid intelligence Gc = c(110, 115, 119, 103), # crystallised intelligence Gs = c(112, 102, 108, 99) # processing speed ) rownames(dataset) <- paste0("person", 1:4) dataset tFrame(dataset)
Removes a package from the search path, using the same
naming convention as library.
unlibrary(package)unlibrary(package)
package |
The name of the package to unload, with or without quotes. |
Calls detach on the named package. Unlike
detach, which requires the full "package:name" string,
unlibrary accepts the bare package name (with or without quotes),
matching the syntax of library. Only the named package is
unloaded; dependencies are not affected.
Called for its side effect of removing the package from the search
path. Returns the result of detach invisibly.
if (FALSE) { # after loading a package with library(), unload it with unlibrary() unlibrary(MASS) }if (FALSE) { # after loading a package with library(), unload it with unlibrary() unlibrary(MASS) }
Prints a summary of all objects in the workspace, showing each object's name, class, and size.
who(expand = FALSE)who(expand = FALSE)
expand |
Set to |
Shows each object's name, class, and size. For objects with
explicit dimensions (e.g., data frames, matrices) the size is shown as
rows x columns; for other objects it is the length. Size is only shown
for objects whose mode is numeric, character, logical,
complex, or list.
Shows more information than objects (especially for variables
inside data frames) but less detail than ls.str.
Prints the workspace summary and invisibly returns the underlying
data (a data frame with columns Name, Class, and Size),
which can be assigned to a variable and inspected if needed.
cats <- 4 mood <- "happy" who() dataset <- data.frame( hi = c("hello", "cruel", "world"), pi = c(3, 1, 4) ) who() who(expand = TRUE)cats <- 4 mood <- "happy" who() dataset <- data.frame( hi = c("hello", "cruel", "world"), pi = c(3, 1, 4) ) who() who(expand = TRUE)
Reshapes a data frame from wide form (one row per subject) to long form (one row per observation), using variable names to determine the structure.
wideToLong(data, within = "within", sep = "_", split = TRUE)wideToLong(data, within = "within", sep = "_", split = TRUE)
data |
A wide-form data frame with one row per subject (or experimental
unit). Variables whose names contain |
within |
A character string, or vector of strings, giving the name(s)
to use for the within-subject factor column(s) in the output. Defaults to
|
sep |
The separator string used in the wide-form variable names to
separate the measure name from the factor level(s). Defaults to |
split |
Set to |
This function is the companion to longToWide. It
determines the reshape structure from the variable names rather than
requiring an explicit formula.
The naming scheme for repeated-measures variables places the measure name
first, followed by the factor level(s), all joined by sep. For
example, variables named accuracy_t1 and accuracy_t2 indicate
a measure called accuracy recorded at two time points (t1 and
t2). After reshaping, the long-form output contains one column called
accuracy and a factor column (named by the within argument)
with levels t1 and t2.
Designs with multiple within-subject factors are supported. For example,
MRT_cond1_day1 encodes measure MRT at level cond1 of
one factor and day1 of another. Supply within = c("condition",
"day") to name both output columns. Multiple measured variables per
observation (e.g., both MRT and PC) are also supported.
A long-form data frame with one row per observation.
# simple design: accuracy measured at two time points for 4 participants wide <- data.frame( id = 1:4, accuracy_t1 = c(.15, .50, .78, .55), accuracy_t2 = c(.55, .32, .99, .60) ) wideToLong(wide, "time") # complex design: two measures (MRT, PC), two conditions, two days wide2 <- data.frame( id = 1:4, gender = factor(c("male", "male", "female", "female")), MRT_cond1_day1 = c(415, 500, 478, 550), MRT_cond2_day1 = c(455, 532, 499, 602), MRT_cond1_day2 = c(400, 490, 468, 502), MRT_cond2_day2 = c(450, 518, 474, 588), PC_cond1_day1 = c(79, 83, 91, 75), PC_cond2_day1 = c(82, 86, 90, 78), PC_cond1_day2 = c(88, 92, 98, 89), PC_cond2_day2 = c(93, 97, 100, 95) ) # default: condition and day become separate columns wideToLong(wide2, within = c("condition", "day")) # alternative: keep condition and day as one combined column wideToLong(wide2, split = FALSE)# simple design: accuracy measured at two time points for 4 participants wide <- data.frame( id = 1:4, accuracy_t1 = c(.15, .50, .78, .55), accuracy_t2 = c(.55, .32, .99, .60) ) wideToLong(wide, "time") # complex design: two measures (MRT, PC), two conditions, two days wide2 <- data.frame( id = 1:4, gender = factor(c("male", "male", "female", "female")), MRT_cond1_day1 = c(415, 500, 478, 550), MRT_cond2_day1 = c(455, 532, 499, 602), MRT_cond1_day2 = c(400, 490, 468, 502), MRT_cond2_day2 = c(450, 518, 474, 588), PC_cond1_day1 = c(79, 83, 91, 75), PC_cond2_day1 = c(82, 86, 90, 78), PC_cond1_day2 = c(88, 92, 98, 89), PC_cond2_day2 = c(93, 97, 100, 95) ) # default: condition and day become separate columns wideToLong(wide2, within = c("condition", "day")) # alternative: keep condition and day as one combined column wideToLong(wide2, split = FALSE)