| Title: | R for Non-Programmers Companion |
|---|---|
| Description: | The official companion to the book 'R For Non-Programmers (R4NP)'. It includes datasets, functions and lots of exercises for the book: <https://r4np.com>. |
| Authors: | Daniel Dauber [aut, cre] (ORCID: <https://orcid.org/0000-0003-4324-4796>) |
| Maintainer: | Daniel Dauber <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.2.1 |
| Built: | 2026-11-27 22:55:30 UTC |
| Source: | https://github.com/ddauber/r4np |
A dataset which contains information about alcohol consumption across various countries.
alcoholalcohol
A data frame with 936 rows and 4 variables:
Country of origin of participant
Country code related to the country-of-origin of participant
The year in which data was collected
Indicates the liters of pure alcohol consumed by individuals of 15+ years of age in the previous year.
Multiple sources compiled by World Bank (2024) – processed by Our World in Data. “Total alcohol consumption per capita – In liters of pure alcohol, projected estimates, 15+ years of age”, Url: https://ourworldindata.org/alcohol-consumption. World Health Organization (via World Bank), “World Development Indicators”, Url: https://datacatalog.worldbank.org/search/dataset/0037712/World-Development-Indicators.
A dataset which contains information about alcohol consumption across various countries.
alcohol_2019alcohol_2019
A data frame with 188 rows and 4 variables:
Country of origin of participant
Country code related to the country-of-origin of participant
The year in which data was collected
Indicates the liters of pure alcohol consumed by individuals of 15+ years of age in the previous year.
Multiple sources compiled by World Bank (2024) – processed by Our World in Data. “Total alcohol consumption per capita – In liters of pure alcohol, projected estimates, 15+ years of age”, Url: https://ourworldindata.org/alcohol-consumption. World Health Organization (via World Bank), “World Development Indicators”, Url: https://datacatalog.worldbank.org/search/dataset/0037712/World-Development-Indicators.
This dataset contains English comments by students about their study experiences at a fictitious university.
commentscomments
A data frame with 209 rows and 1 variable:
Comments by students about their study experiences.
Provides a score from 1-10 regarding the level of social inclusion experienced by students. | 1 ("I feel lonely") to 10 = ("I feel par of the campus community").
Fictitious dataset created for educational purposes.
A dataset which contains COVID cases and deaths, vaccination information and public health social measures (PHSM) for each country covered by the WHO.
covidcovid
A data frame with 142674 rows and 17 variables:
Date when cases, deaths, PHSM, etc. were reported
ISO three-digit country identifier
Name of country
# of new COVID cases
Total number of COVID cases
Total number of deaths due to COVID
Total number of fully vaccinated people
Index of mask measures implemented (0-100)
Index of travel measures implemented (0-100)
Index of gathering measures implemented (0-100)
Index of school measures implemented (0-100)
Index of business measures implemented (0-100)
Index of movement measures implemented (0-100)
Global index of overall measures implemented (0-100)
Lists all measures in place according to WHO taxanomy
Region a country is located in (WHO classification)
Population of a country as of 2016
World Health Organisation (WHO). Dataset retrieved on 2nd February 2023 from: https://covid19.who.int/info/. WHO data is licensed under Creative Commons Attribution 4.0 International License (CC BY 4.0).
Automatically create folders for a project
create_project_folder()create_project_folder()
Automatically generate a project folder structure in the working directory of your R session.
The EQLS dataset is a pan-European survey that captures both the objective conditions of citizens' lives (e.g., employment, income, health) and their subjective perceptions, including life satisfaction and happiness.
eqlseqls
A data frame with 79270 rows and 45 variables:
Participant unique ID
Data was collected in several waves, 2007 and 2011. This allows comparing countries over time.
Name of country participants resides in.
Country ISO code
Marital status
Item: Number of children of your own
Item: The area in which you live is...?
Age of respondent
Highest level of education completed
Gender of participant
Employment status
Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").
Item: How frequently do you: Attend religious services, apart from weddings, funerals or christenings? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Use the Internet other than for work? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Take part in sports or physical exercise? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Participate in social activities of a club, society, or an association? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How often unpaid voluntary work in the last 12 months: Community and social services? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Education, cultural, sports or professional organisation? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Social movements or charities? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Political parties, trade unions? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Other voluntary organisations? | 1 ("Every week") to 5 = ("Not at all").
Volunteering frequency | 1 ("Every week") to 5 = ("Not at all").
Item: I feel left out of society.
Item: Life has become so complicated today that I almost can’t find my way | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: I feel that the value of what I do is not recognised by others | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: Some people look down on me because of my job situation or income | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: I feel close to people in the area where I live | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Social Exclusion Index
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt cheerful and in good spirits | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt calm and relaxed | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt active and vigorous | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I woke up feeling fresh and rested | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - My daily life has been filled with things that interest me | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt particularly tense | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt lonely | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt downhearted and depressed | 1 ("All of the time") to 6 = ("At no time").
WHO-5 mental wellbeing index
Item: I have come home from work too tired to do some of the household jobs which need to be done | 1 ("Several times a week") to 6 = ("Less often/rarely").
Item: It has been difficult for me to fulfil my family responsibilities because of the amount of time I spend on the job | 1 ("Several times a week") to 6 = ("Less often/rarely").
Item: I have found it difficult to concentrate at work because of my family responsibilities | 1 ("Several times a week") to 6 = ("Less often/rarely").
Work-life balance conflict
Item: How many hours do you normally work per week in your main job? | (80hrs or more).
Item: About how many hours per week did you work in this additional job? | (60hrs or more).
The total number of working hours.
European Foundation for the Improvement of Living and Working Conditions. (2015). European Quality of Life Time Series, 2007 and 2011: Open Access. UK Data Service. SN: 7724, doi:10.5255/UKDA-SN-7724-1.
The EQLS dataset is a pan-European survey that captures both the objective conditions of citizens' lives (e.g., employment, income, health) and their subjective perceptions, including life satisfaction and happiness.
eqls_2011eqls_2011
A data frame with 43636 rows and 44 variables:
Participant unique ID
Data was collected in several waves, 2007 and 2011. This allows comparing countries over time.
Name of country participants resides in.
Country ISO code
Marital status
Item: Number of children of your own
Item: The area in which you live is...?
Age of respondent
Highest level of education completed
Gender of participant
Employment status
Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").
Item: How frequently do you: Attend religious services, apart from weddings, funerals or christenings? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Use the Internet other than for work? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Take part in sports or physical exercise? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How frequently do you: Participate in social activities of a club, society, or an association? | 1 ("Every day or almost every day") to 5 = ("Never").
Item: How often unpaid voluntary work in the last 12 months: Community and social services? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Education, cultural, sports or professional organisation? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Social movements or charities? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Political parties, trade unions? | 1 ("Every week") to 5 = ("Not at all").
Item: How often unpaid voluntary work in the last 12 months: Other voluntary organisations? | 1 ("Every week") to 5 = ("Not at all").
Volunteering frequency | 1 ("Every week") to 5 = ("Not at all").
Item: I feel left out of society.
Item: Life has become so complicated today that I almost can’t find my way | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: I feel that the value of what I do is not recognised by others | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: Some people look down on me because of my job situation or income | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Item: I feel close to people in the area where I live | 1 ("Strongly agree") to 5 = ("Strongly disagree").
Social Exclusion Index
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt cheerful and in good spirits | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt calm and relaxed | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt active and vigorous | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I woke up feeling fresh and rested | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - My daily life has been filled with things that interest me | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt particularly tense | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt lonely | 1 ("All of the time") to 6 = ("At no time").
Item: Which is closest to how you have been feeling over the last 2 weeks? - I have felt downhearted and depressed | 1 ("All of the time") to 6 = ("At no time").
WHO-5 mental wellbeing index
Item: I have come home from work too tired to do some of the household jobs which need to be done | 1 ("Several times a week") to 6 = ("Less often/rarely").
Item: It has been difficult for me to fulfil my family responsibilities because of the amount of time I spend on the job | 1 ("Several times a week") to 6 = ("Less often/rarely").
Item: I have found it difficult to concentrate at work because of my family responsibilities | 1 ("Several times a week") to 6 = ("Less often/rarely").
Work-life balance conflict
Item: How many hours do you normally work per week in your main job? | (80hrs or more).
Item: About how many hours per week did you work in this additional job? | (60hrs or more).
The total number of working hours.
European Foundation for the Improvement of Living and Working Conditions. (2015). European Quality of Life Time Series, 2007 and 2011: Open Access. UK Data Service. SN: 7724, doi:10.5255/UKDA-SN-7724-1.
The EQLS dataset is a pan-European survey that captures both the objective conditions of citizens' lives (e.g., employment, income, health) and their subjective perceptions, including life satisfaction and happiness.
eqls_country_2011eqls_country_2011
A data frame with 32 rows and 5 variables:
Name of country participants resides in.
Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").
Social Exclusion Index
WHO-5 mental wellbeing index
Work-life balance conflict
European Foundation for the Improvement of Living and Working Conditions. (2015). European Quality of Life Time Series, 2007 and 2011: Open Access. UK Data Service. SN: 7724, doi:10.5255/UKDA-SN-7724-1.
A dataset containing information about students' social integration (si) experience at their Higher Education Institutions and their communication skills (cs) development. For cs, scores of 'actualy experience' and 'importance to me' are available. This dataset only contains a random sample of 300 observations out of well over 12,000 students as of August 2021.
gepgep
A data frame with 300 rows and 12 variables:
Age of participant
Gender of participant
Degree level at the time of the research project
Extent to which participants have opportunities to socialise with people from diverse cultural backgrounds | 1 ("not at all") to 6 ("very much")
Extent to which participants have supportive friends with a diverse cultural background | 1 ("not at all") to 6 ("very much")
Extent to which participants take time to socialise with people from diverse cultural backgrounds | 1 ("not at all") to 6 ("very much")
Extent to which participants perceive improving in explaining ideas to others (importance) | 1 ("not at all") to 6 ("very much")
Extent to which participants are able to clarify what others mean (importance) | 1 ("not at all") to 6 ("very much")
Extent to which participants learn about other students communication styles (importance) | 1 ("not at all") to 6 ("very much")
Extent to which participants perceive improving in explaining ideas to others (experience) | 1 ("not at all") to 6 ("very much")
Extent to which participants are able to clarify what others mean (experience) | 1 ("not at all") to 6 ("very much")
Extent to which participants learn about other students communication styles (experience) | 1 ("not at all") to 6 ("very much")
Global Education Profiler (https://warwick.ac.uk/gep)
A dataset which contains data about Halloween consumer behaviour across the US, the UK and Germany.
halloweenhalloween
A data frame with 5982 rows and 3 variables:
Expenses related to Halloween candies
Distance covered while 'Trick-or-treating'
Participants country of residence
Ripped from the dying hands of the Pumpkin Lord.
A selected range of variables from the the Health Index for England dataset, which is a comprehensive measure of national health, considering outcomes, behaviors, personal circumstances, and environmental factors. It provides a single health score and allows detailed breakdowns by location and topic, facilitating comparisons over time.
hiehie
A data frame with 2149 rows and 21 variables:
The area the data was collected from.
Regional categorisation of areas.
The year data was collected.
The average score of respondents (16+) on how meaningful they find their life's activities.
The percentage of 5-year-olds meeting the expected early learning goals in personal, social, emotional, physical, communication, language, mathematics, and literacy at the end of the Early Years Foundation Stage (EYFS).
The average anxiety score of respondents (16+) when asked how they felt the day before.
The average happiness score of respondents (16+) when asked how they felt the day before.
The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.
The percentage of people reporting high blood pressure (hypertension) - not based on GP records but survey responses.
The percentage of households considered overcrowded, based on a standard calculation comparing the number of required rooms to the actual number of rooms.
Period life expectancy at birth is the average number of years a person born in a specific year and area would live if they experienced that area's current age-specific mortality rates throughout their life.
The average life satisfaction score of respondents aged 16 and over.
The number of police-recorded low-level crimes per 1,000 people, with bicycle theft and shoplifting used as indicators of overall rates.
The percentage of people reporting a mental health condition, such as depression or anxiety- not based on GP records but survey responses.
The percentage of adults (18+) who are overweight or obese, based on self-reported height and weight in a survey.
The percentage of children in Reception (aged 4-5) and Year 6 (aged 10-11) who are overweight or obese.
The percentage of adults (19+) reporting physical activity of 150 minutes or more per week.
The number of people sleeping outdoors on a single night in October or November, per 100,000 residents.
The percentage of adults (18+) who currently smoke cigarettes.
The percentage of adults (16+) actively seeking work in the past four weeks and available to start within two weeks, relative to the economically active population.
The percentage of 16 and 17-year-olds in sustained education, employment, or apprenticeships one year after key stage 4 (after school Year 11).
Office for National Statistics (ONS), released 16 June 2023, ONS website, Health Index Scores, England, Url: https://www.ons.gov.uk/peoplepopulationandcommunity/healthandsocialcare/healthandwellbeing/datasets/healthindexscoresengland.
A selected range of variables from the the Health Index for England dataset, which is a comprehensive measure of national health, considering outcomes, behaviors, personal circumstances, and environmental factors. It provides a single health score and allows detailed breakdowns by location and topic, facilitating comparisons over time. This dataset only contains data collected in 2015 and 2021.
hie_15_21hie_15_21
A data frame with 614 rows and 6 variables:
The area the data was collected from.
The year data was collected.
The average anxiety score of respondents (16+) when asked how they felt the day before.
The average happiness score of respondents (16+) when asked how they felt the day before.
The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.
The average life satisfaction score of respondents aged 16 and over.
Office for National Statistics (ONS), released 16 June 2023, ONS website, Health Index Scores, England, Url: https://www.ons.gov.uk/peoplepopulationandcommunity/healthandsocialcare/healthandwellbeing/datasets/healthindexscoresengland.
A selected range of variables from the the Health Index for England dataset, which is a comprehensive measure of national health, considering outcomes, behaviors, personal circumstances, and environmental factors. It provides a single health score and allows detailed breakdowns by location and topic, facilitating comparisons over time. This dataset only contains data collected in 2021.
hie_2021hie_2021
A data frame with 307 rows and 21 variables:
The area the data was collected from.
Regional categorisation of areas.
The year data was collected.
The average score of respondents (16+) on how meaningful they find their life's activities.
The percentage of 5-year-olds meeting the expected early learning goals in personal, social, emotional, physical, communication, language, mathematics, and literacy at the end of the Early Years Foundation Stage (EYFS).
The average anxiety score of respondents (16+) when asked how they felt the day before.
The average happiness score of respondents (16+) when asked how they felt the day before.
The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.
The percentage of people reporting high blood pressure (hypertension) - not based on GP records but survey responses.
The percentage of households considered overcrowded, based on a standard calculation comparing the number of required rooms to the actual number of rooms.
Period life expectancy at birth is the average number of years a person born in a specific year and area would live if they experienced that area's current age-specific mortality rates throughout their life.
The average life satisfaction score of respondents aged 16 and over.
The number of police-recorded low-level crimes per 1,000 people, with bicycle theft and shoplifting used as indicators of overall rates.
The percentage of people reporting a mental health condition, such as depression or anxiety- not based on GP records but survey responses.
The percentage of adults (18+) who are overweight or obese, based on self-reported height and weight in a survey.
The percentage of children in Reception (aged 4-5) and Year 6 (aged 10-11) who are overweight or obese.
The percentage of adults (19+) reporting physical activity of 150 minutes or more per week.
The number of people sleeping outdoors on a single night in October or November, per 100,000 residents.
The percentage of adults (18+) who currently smoke cigarettes.
The percentage of adults (16+) actively seeking work in the past four weeks and available to start within two weeks, relative to the economically active population.
The percentage of 16 and 17-year-olds in sustained education, employment, or apprenticeships one year after key stage 4 (after school Year 11).
Office for National Statistics (ONS), released 16 June 2023, ONS website, Health Index Scores, England, Url: https://www.ons.gov.uk/peoplepopulationandcommunity/healthandsocialcare/healthandwellbeing/datasets/healthindexscoresengland.
A dataset which contains real-world pre- and post-training test scores for Intercultural Communication trainees. Participants names were replaced with random names.
ic_trainingic_training
A data frame with 96 rows and 11 variables:
Random names created with randomName package
Defines whether a test was performed before or after training
Level of confidence in communication with people from diverse cultural backgrounds
Level of confidence in working with people from diverse cultural backgrounds
Level of confidence in leading people from diverse cultural backgrounds
Factorised 'communication' with levels "yes and "no"
Factorised 'teamwork' with levels "yes and "no"
Factorised 'leadership' with levels "yes and "no"
Factorised 'communication' with levels "high", "medium", and "low"
Factorised 'teamwork' with levels "high", "medium", and "low"
Factorised 'leadership' with levels "high", "medium", and "low"
Research conducted at the University of Warwick (2018)
Installs every R package used in the book R For Non-Programmers: A Guide for Social Scientists in one go. Packages that are missing are installed, packages that are out of date are updated, and packages that are already up to date are left alone. You can run this function again at any time to bring all packages up to date.
install_r4np()install_r4np()
install_r4np() uses the pak package to
install packages, because it is fast, prefers ready-built (binary)
packages and, on Linux, can install the system libraries some packages
need. If pak is not installed yet, it is installed first. If pak
cannot be installed or fails, the function falls back to
utils::install.packages().
Packages are installed from the CRAN repository set in your R options
(or https://cloud.r-project.org if none is set). gradethis is not on
CRAN and is installed from https://rstudio.r-universe.dev.
Updating packages that are already loaded can fail, especially on
Windows. It is best to run install_r4np() in a fresh R session (in
RStudio: Session > Restart R).
The following packages are installed:
broom: Turns the output of statistical tests and models into tibbles.
car: Companion to applied regression, e.g. for Levene's test and VIFs.
correlation: Computes many kinds of correlations, such as partial, polychoric or Bayesian correlations.
effectsize: Computes and converts effect sizes, such as Cohen's d, r or odds ratios.
exact2x2: Computes the exact McNemar test.
ggdist: ggplot2 extension to plot distributions and uncertainty.
ggforce: ggplot2 extension with additional geoms.
ggmosaic2: ggplot2 extension to build mosaic plots.
ggraph: Builds network graphs with ggplot2.
ggridges: ggplot2 extension to build ridge plots.
gradethis: Checks answers in the interactive exercises (tutorials) that come with this package.
igraph: Creates and analyses networks; used together with ggraph.
infer: Performs statistical inference using a tidy, pipe-friendly workflow.
janitor: Cleans column names, builds frequency tables and crosstabs, and finds duplicates.
jtools: Summarises and presents the results of regression analyses.
lavaan: Fits latent variable models, such as confirmatory factor analysis and structural equation models.
learnr: Runs the interactive exercises (tutorials) that come with this package.
lubridate: Works with dates and times.
mi: Imputes missing values in a Bayesian framework.
mice: Imputes missing values with multivariate imputation by chained equations (MICE).
modelr: Pipe-friendly functions for modelling data.
naniar: Explores and visualises missing values.
parameters: Extracts parameters from regression models.
patchwork: Combines several ggplots into one plot.
performance: Computes performance indices and checks assumptions of regression models.
psych: Toolbox for personality, psychometric and experimental psychology research.
pwr: Computes statistical power for common tests.
rcompanion: Additional statistical functions, such as effect sizes.
rstatix: Pipe-friendly functions for common statistical tests.
scales: Formats ggplot2 axes and labels.
see: Visualises output from easystats packages.
simputation: Simple imputation methods for missing data.
skimr: Pipe-friendly summary statistics that display nicely in the console.
tidytext: Text mining using tidy data principles.
tidyverse: Installs the core tidyverse packages, such as dplyr, ggplot2 and tidyr.
wesanderson: Colour palettes inspired by Wes Anderson films for ggplot2.
wordcloud: Generates word clouds from text data.
Invisibly, a character vector with the names of all packages that are installed after the function has run.
## Not run: # Run this line of code to install or update all relevant packages install_r4np() ## End(Not run)## Not run: # Run this line of code to install or update all relevant packages install_r4np() ## End(Not run)
This function performs a Shapiro-Wilk normality test on multiple variables in a dataframe. It returns the results in a tidy format.
ntest(df, cols)ntest(df, cols)
df |
A dataframe containing the data to be tested. It can be supplied
directly ( |
cols |
< |
Before running any tests, the function checks that df is a
dataframe, that all selected columns are numeric, and that each variable
has between 3 and 5000 non-missing observations (the range shapiro.test()
accepts) and is not constant. If any check fails, the function stops with
an error message explaining which variables are affected. It then performs
the Shapiro-Wilk test on each variable and returns a formatted dataframe
with the test results.
If df is a grouped dataframe, the grouping is ignored and all
observations are tested together. Use ntest_by() to test each group
separately.
A tibble with one row per variable and the columns variable,
statistic, p.value and method.
ntest_by() to run normality tests for grouped data
Other assumption tests:
ntest_by(),
vtest()
# Test a single variable ntest(df = mtcars, cols = mpg) # Test several variables, piping the data into the function mtcars |> ntest(c(mpg, disp, hp))# Test a single variable ntest(df = mtcars, cols = mpg) # Test several variables, piping the data into the function mtcars |> ntest(c(mpg, disp, hp))
This function performs a Shapiro-Wilk normality test on multiple variables in a dataframe by groups.
ntest_by(df, cols, group)ntest_by(df, cols, group)
df |
A dataframe containing the data to be tested. It can be supplied
directly ( |
cols |
< |
group |
< |
Before running any tests, the function checks that df is a
dataframe, that all variables in cols are numeric, and that within
each group every variable has between 3 and 5000 non-missing
observations (the range shapiro.test() accepts) and is not constant.
With several grouping variables, these checks apply to every
combination of their values. If any check fails, the function stops
with an error message explaining which groups or variables are affected.
It then performs the Shapiro-Wilk test for each variable within each
group and returns the results in a tidy format.
Groups are defined only by group. If df is already a grouped
dataframe, that grouping is ignored and a short message says so (unless
it matches group).
A tibble with one row per group and variable, containing the
grouping variable(s) and the columns variable, statistic, p.value
and method.
ntest() to run normality tests for ungrouped data
Other assumption tests:
ntest(),
vtest()
# Perform a normality test for each group ntest_by(df = mtcars, cols = mpg, group = cyl) # Test several variables by group, piping the data into the function iris |> ntest_by(c(Sepal.Length, Sepal.Width), Species) # Test each combination of two grouping variables (engine shape and # transmission) ntest_by(mtcars, mpg, group = c(vs, am))# Perform a normality test for each group ntest_by(df = mtcars, cols = mpg, group = cyl) # Test several variables by group, piping the data into the function iris |> ntest_by(c(Sepal.Length, Sepal.Width), Species) # Test each combination of two grouping variables (engine shape and # transmission) ntest_by(mtcars, mpg, group = c(vs, am))
The People and Nature Survey for England is a study conducted to gather data on how people use, enjoy, and benefit from the natural environment in England.
pplnatpplnat
A data frame with 3585 rows and 19 variables:
Different regions in England where data was collected.
Data was collected in several waves. This provides opportunities to analyse data over time.
Item: In the last 12 months, how often, on average have you spent free time outside in green and natural spaces?
Item: How much do you agree or disagree with the following statements relating to green and natural spaces locally: Within easy walking distance. | 1 ("Strongly disagree") to 5 = ("Strongly agree").
Item: How much do you agree or disagree with the following statements relating to green and natural spaces locally: Places where I can relax and unwind. | 1 ("Strongly disagree") to 5 = ("Strongly agree").
Item: How much do you agree or disagree with the following statements relating to green and natural spaces locally: A high enough standard to want to spend time in. | 1 ("Strongly disagree") to 5 = ("Strongly agree").
Item: How important is protecting the environment to you personally? | 1 ("Not at all important") to 5 = ("Very important").
Item: How much do you agree or disagree with the following statement? I am concerned about damage to the natural environment. | 1 ("Not at all important") to 5 = ("Very important").
Item: How often do you do the actions below when you have the opportunity? When I see litter, I pick it up. | 1 ("Never") to 5 = ("Always / whenever I have the opportunity").
Item: How often do you do the actions below when you have the opportunity? I vote for political parties with strong environmental policies | 1 ("Never") to 5 = ("Always / whenever I have the opportunity").
Item: Are you going to make changes to your lifestyle to protect the environment (for example by recycling rather than throwing things away, using your car less and buying local food)?
Item: How often do you feel lonely? | 1 ("Never") to 5 = ("Often / always").
Item: Overall, how satisfied are you with your life nowadays? | 1 ("Not at all") to 10 = ("Completely").
Item: Overall, how worthwhile are the things you do in your life? | 1 ("Not at all") to 10 = ("Completely").
Item: How happy were you feeling yesterday? | 1 ("Not at all") to 10 = ("Completely").
Item: How anxious were you feeling yesterday? | 1 ("Not at all") to 10 = ("Completely").
This is the reverse-scored item for wb_worried_anxious.
Natural connectedness scale (latent variable based on ncs items).
A higher score implies higher natural connectedness.
Wellbeing (latent variable based on wb items).
A higher score implies higher wellbeing
Natural England. (2023). People and Nature Survey for England, 2020-2023: Open Access. 3rd Edition. UK Data Service. SN: 9092. doi:10.5255/UKDA-SN-9092-3
A dataset which contains start and end dates regarding the completion of a questionnaire.
quest_timequest_time
A data frame with 84 rows and 3 variables:
Unique identifier of participant
The date and time at which a participant started the questionnaire
The date and time at which a participant finished the questionnaire
A random selection of observations from the Global Education Profiler (GEP).
This dataset contains English comments by students about their study experiences at a fictitious university.
reading_timereading_time
A data frame with 209 rows and 3 variable:
Gender of the participant
Degree level of participant
Reading time per week measured in minutes
Fictitious dataset created for educational purposes.
A dataset to demonstrate the Simpson's Paradox.
simpsonsimpson
A data frame with 300 rows and 3 variables:
Student's change in performance at school.
Participant's change in happiness
Group a participant belongs to, i.e. Teacher, Student, or Parent
Dataset created with correlation::simulate_simpson()
This dataset contains information about employees' salary, their working experience and time spend on mindfulness practices.
swmswm
A data frame with 100 rows and 3 variables:
Salary earned (in USD 1000)
Years of working experience
Minutes spent on mindfulness practices in a 5-day working week.
Fictitious dataset created for educational purposes.
This function performs Levene's test for homogeneity of variance on multiple variables in a dataframe. For each variable, it tests whether the variance is the same in all groups. It returns the results in a tidy format.
vtest(df, cols, group, center = c("median", "mean"))vtest(df, cols, group, center = c("median", "mean"))
df |
A dataframe containing the data to be tested. It can be supplied
directly ( |
cols |
< |
group |
< |
center |
The value each group is centred on: |
Levene's test checks the assumption of homogeneity of variance
(also called homoscedasticity), which tests such as the t-test and ANOVA
rely on. For each variable, it measures how far each value is from the
centre (median or mean) of its group and then compares these distances
across groups with a one-way ANOVA. A significant result (e.g.
p.value < 0.05) suggests that the variances differ between groups. The
results are identical to those of car::leveneTest().
Before running any tests, the function checks that df is a dataframe,
that all variables in cols are numeric, that there are at least two
groups, that each group has at least two non-missing values, and that
the values are not identical within every group. If any check fails, the
function stops with an error message explaining which variables or
groups are affected.
Missing values are handled separately for each variable, so a missing
value in one variable does not remove that row from the tests of other
variables. Rows with a missing value in group are removed, and a short
message says how many.
Groups are defined only by group. If df is already a grouped
dataframe, that grouping is ignored and a short message says so (unless
it matches group).
A tibble with one row per variable and the columns variable,
statistic (the F statistic), df1 and df2 (the degrees of freedom),
p.value and method.
ntest() and ntest_by() to test the assumption of normality
Other assumption tests:
ntest(),
ntest_by()
# Compare the variance of mpg across the groups of cyl vtest(df = mtcars, cols = mpg, group = cyl) # Test several variables, piping the data into the function mtcars |> vtest(c(mpg, disp, hp), cyl) # Use the mean instead of the median (the original Levene's test) vtest(mtcars, mpg, cyl, center = "mean") # Compare all combinations of two grouping variables vtest(mtcars, mpg, group = c(cyl, am))# Compare the variance of mpg across the groups of cyl vtest(df = mtcars, cols = mpg, group = cyl) # Test several variables, piping the data into the function mtcars |> vtest(c(mpg, disp, hp), cyl) # Use the mean instead of the median (the original Levene's test) vtest(mtcars, mpg, cyl, center = "mean") # Compare all combinations of two grouping variables vtest(mtcars, mpg, group = c(cyl, am))
A dataset which contains selected data from the World Value Survey. This data was obtained in October 2020.
wvswvs
A data frame with 8564 rows and 7 variables:
Unique identifier for each participant
Country name, partially abbreviated
Gender of participant
Age of participant at the time of data collection
Relationship status of participants
Item: Some people feel they have completely free choice and control over their lives, while other people feel that what they do has no real effect on what happens to them. Indicate how much freedom of choice and control you feel you have over the way your life turns out | 1 ("no choice at all") to 10 ("a great deal of choice").
Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)
World Value Survey (WVS) (https://www.worldvaluessurvey.org)
A cleaned version of the wvs dataset.
wvs_nonawvs_nona
A data frame with 8564 rows and 6 variables:
Country name, partially abbreviated
Gender of participant
Age of participant at the time of data collection
Relationship status of participants
Item: Some people feel they have completely free choice and control over their lives, while other people feel that what they do has no real effect on what happens to them. Indicate how much freedom of choice and control you feel you have over the way your life turns out | 1 ("no choice at all") to 10 ("a great deal of choice").
Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)
World Value Survey (WVS) (https://www.worldvaluessurvey.org)
A dataset excerpt from the World Value Survey including 3 countries over 7 waves of data collection.
wvs_waveswvs_waves
A data frame with 2100 rows and 5 variables:
Unique ID for each participant
Random names created with randomName package
Defines whether a test was performed before or after training
Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)
Item: Some people feel they have completely free choice and control over their lives, while other people feel that what they do has no real effect on what happens to them. Indicate how much freedom of choice and control you feel you have over the way your life turns out | 1 ("no choice at all") to 10 ("a great deal of choice").
World Value Survey (WVS). Data retrieve from https://www.worldvaluessurvey.org