Package 'r4np'

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

Help Index


Alcohol consumption around the world (2000-2019)

Description

A dataset which contains information about alcohol consumption across various countries.

Usage

alcohol

Format

A data frame with 936 rows and 4 variables:

country

Country of origin of participant

code

Country code related to the country-of-origin of participant

year

The year in which data was collected

consumption

Indicates the liters of pure alcohol consumed by individuals of 15+ years of age in the previous year.

Source

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.


Alcohol consumption around the world (2019)

Description

A dataset which contains information about alcohol consumption across various countries.

Usage

alcohol_2019

Format

A data frame with 188 rows and 4 variables:

country

Country of origin of participant

code

Country code related to the country-of-origin of participant

year

The year in which data was collected

consumption

Indicates the liters of pure alcohol consumed by individuals of 15+ years of age in the previous year.

Source

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.


Student Life (Open comments)

Description

This dataset contains English comments by students about their study experiences at a fictitious university.

Usage

comments

Format

A data frame with 209 rows and 1 variable:

comment

Comments by students about their study experiences.

social_inclusion

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").

Source

Fictitious dataset created for educational purposes.


COVID-19 DATA

Description

A dataset which contains COVID cases and deaths, vaccination information and public health social measures (PHSM) for each country covered by the WHO.

Usage

covid

Format

A data frame with 142674 rows and 17 variables:

date_reported

Date when cases, deaths, PHSM, etc. were reported

iso3

ISO three-digit country identifier

country

Name of country

new_cases

# of new COVID cases

cumulative_cases

Total number of COVID cases

cumulative_deaths

Total number of deaths due to COVID

fully_vaccinated

Total number of fully vaccinated people

masks

Index of mask measures implemented (0-100)

travel

Index of travel measures implemented (0-100)

gatherings

Index of gathering measures implemented (0-100)

schools

Index of school measures implemented (0-100)

businesses

Index of business measures implemented (0-100)

movements

Index of movement measures implemented (0-100)

global_index

Global index of overall measures implemented (0-100)

measures_in_place

Lists all measures in place according to WHO taxanomy

region

Region a country is located in (WHO classification)

population

Population of a country as of 2016

Source

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

Description

Automatically create folders for a project

Usage

create_project_folder()

Details

Automatically generate a project folder structure in the working directory of your R session.


European Quality of Life Survey Time Series, 2007 and 2011

Description

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.

Usage

eqls

Format

A data frame with 79270 rows and 45 variables:

id

Participant unique ID

wave

Data was collected in several waves, 2007 and 2011. This allows comparing countries over time.

country_name

Name of country participants resides in.

iso_code

Country ISO code

marital_status

Marital status

num_of_children

Item: Number of children of your own

rural_urban_living

Item: The area in which you live is...?

age_category

Age of respondent

education

Highest level of education completed

gender

Gender of participant

employment

Employment status

trust_people

Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").

freq_rel_service_use

Item: How frequently do you: Attend religious services, apart from weddings, funerals or christenings? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_internet_personal

Item: How frequently do you: Use the Internet other than for work? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_sports

Item: How frequently do you: Take part in sports or physical exercise? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_social_activities

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").

vol_community_service

Item: How often unpaid voluntary work in the last 12 months: Community and social services? | 1 ("Every week") to 5 = ("Not at all").

vol_education_cult_org

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").

vol_social_charities

Item: How often unpaid voluntary work in the last 12 months: Social movements or charities? | 1 ("Every week") to 5 = ("Not at all").

vol_political_parties

Item: How often unpaid voluntary work in the last 12 months: Political parties, trade unions? | 1 ("Every week") to 5 = ("Not at all").

vol_other_organisation

Item: How often unpaid voluntary work in the last 12 months: Other voluntary organisations? | 1 ("Every week") to 5 = ("Not at all").

volunteering_frequency

Volunteering frequency | 1 ("Every week") to 5 = ("Not at all").

sei_left_out_soc

Item: I feel left out of society.

sei_life_is_complicated

Item: Life has become so complicated today that I almost can’t find my way | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_not_recognised

Item: I feel that the value of what I do is not recognised by others | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_looked_down

Item: Some people look down on me because of my job situation or income | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_feel_close_to_people

Item: I feel close to people in the area where I live | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei

Social Exclusion Index

mwbi_felt_cheerful

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").

mwbi_felt_calm

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").

mwbi_felt_active

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").

mwbi_felt_fresh

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").

mwbi_life_is_interesting

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").

mwbi_felt_tense

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").

mwbi_felt_lonely

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").

mwbi_felt_downhearted

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").

mwbi

WHO-5 mental wellbeing index

wlbc_too_tired_household

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").

wlbc_fam_responsibilities

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").

wlbc_cannot_focus_on_work

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").

wlbc

Work-life balance conflict

hrs_work_first_job

Item: How many hours do you normally work per week in your main job? | (80hrs or more).

hrs_work_additional_job

Item: About how many hours per week did you work in this additional job? | (60hrs or more).

work_hrs

The total number of working hours.

Source

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.


European Quality of Life Survey Time Series (2011 only)

Description

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.

Usage

eqls_2011

Format

A data frame with 43636 rows and 44 variables:

id

Participant unique ID

wave

Data was collected in several waves, 2007 and 2011. This allows comparing countries over time.

country_name

Name of country participants resides in.

iso_code

Country ISO code

marital_status

Marital status

num_of_children

Item: Number of children of your own

rural_urban_living

Item: The area in which you live is...?

age_category

Age of respondent

education

Highest level of education completed

gender

Gender of participant

employment

Employment status

trust_people

Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").

freq_rel_service_use

Item: How frequently do you: Attend religious services, apart from weddings, funerals or christenings? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_internet_personal

Item: How frequently do you: Use the Internet other than for work? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_sports

Item: How frequently do you: Take part in sports or physical exercise? | 1 ("Every day or almost every day") to 5 = ("Never").

freq_social_activities

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").

vol_community_service

Item: How often unpaid voluntary work in the last 12 months: Community and social services? | 1 ("Every week") to 5 = ("Not at all").

vol_education_cult_org

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").

vol_social_charities

Item: How often unpaid voluntary work in the last 12 months: Social movements or charities? | 1 ("Every week") to 5 = ("Not at all").

vol_political_parties

Item: How often unpaid voluntary work in the last 12 months: Political parties, trade unions? | 1 ("Every week") to 5 = ("Not at all").

vol_other_organisation

Item: How often unpaid voluntary work in the last 12 months: Other voluntary organisations? | 1 ("Every week") to 5 = ("Not at all").

volunteering_frequency

Volunteering frequency | 1 ("Every week") to 5 = ("Not at all").

sei_left_out_soc

Item: I feel left out of society.

sei_life_is_complicated

Item: Life has become so complicated today that I almost can’t find my way | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_not_recognised

Item: I feel that the value of what I do is not recognised by others | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_looked_down

Item: Some people look down on me because of my job situation or income | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei_feel_close_to_people

Item: I feel close to people in the area where I live | 1 ("Strongly agree") to 5 = ("Strongly disagree").

sei

Social Exclusion Index

mwbi_felt_cheerful

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").

mwbi_felt_calm

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").

mwbi_felt_active

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").

mwbi_felt_fresh

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").

mwbi_life_is_interesting

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").

mwbi_felt_tense

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").

mwbi_felt_lonely

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").

mwbi_felt_downhearted

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").

mwbi

WHO-5 mental wellbeing index

wlbc_too_tired_household

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").

wlbc_fam_responsibilities

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").

wlbc_cannot_focus_on_work

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").

wlbc

Work-life balance conflict

hrs_work_first_job

Item: How many hours do you normally work per week in your main job? | (80hrs or more).

hrs_work_additional_job

Item: About how many hours per week did you work in this additional job? | (60hrs or more).

work_hrs

The total number of working hours.

Source

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.


European Quality of Life Survey Time Series (2011 only, country aggregates)

Description

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.

Usage

eqls_country_2011

Format

A data frame with 32 rows and 5 variables:

country_name

Name of country participants resides in.

trust_people

Item: Would you say that most people can be trusted? | 1 ("You cannot be too careful") to 10 = ("Most people can be trusted").

sei

Social Exclusion Index

mwbi

WHO-5 mental wellbeing index

wlbc

Work-life balance conflict

Source

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.


Global Education Profiler (random sample)

Description

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.

Usage

gep

Format

A data frame with 300 rows and 12 variables:

age

Age of participant

gender

Gender of participant

level_of_study

Degree level at the time of the research project

si_socialise_with_people_exp

Extent to which participants have opportunities to socialise with people from diverse cultural backgrounds | 1 ("not at all") to 6 ("very much")

si_supportive_friends_exp

Extent to which participants have supportive friends with a diverse cultural background | 1 ("not at all") to 6 ("very much")

si_time_socialising_exp

Extent to which participants take time to socialise with people from diverse cultural backgrounds | 1 ("not at all") to 6 ("very much")

cs_explain_ideas_imp

Extent to which participants perceive improving in explaining ideas to others (importance) | 1 ("not at all") to 6 ("very much")

cs_find_clarification_imp

Extent to which participants are able to clarify what others mean (importance) | 1 ("not at all") to 6 ("very much")

cs_learn_different_styles_imp

Extent to which participants learn about other students communication styles (importance) | 1 ("not at all") to 6 ("very much")

cs_explain_ideas_exp

Extent to which participants perceive improving in explaining ideas to others (experience) | 1 ("not at all") to 6 ("very much")

cs_find_clarification_exp

Extent to which participants are able to clarify what others mean (experience) | 1 ("not at all") to 6 ("very much")

cs_learn_different_styles_exp

Extent to which participants learn about other students communication styles (experience) | 1 ("not at all") to 6 ("very much")

Source

Global Education Profiler (https://warwick.ac.uk/gep)


Halloween

Description

A dataset which contains data about Halloween consumer behaviour across the US, the UK and Germany.

Usage

halloween

Format

A data frame with 5982 rows and 3 variables:

expenses

Expenses related to Halloween candies

distance

Distance covered while 'Trick-or-treating'

country

Participants country of residence

Source

Ripped from the dying hands of the Pumpkin Lord.


The Health Index for England (2015-2021)

Description

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.

Usage

hie

Format

A data frame with 2149 rows and 21 variables:

area_name

The area the data was collected from.

region

Regional categorisation of areas.

year

The year data was collected.

activities_in_life_are_worthwhile

The average score of respondents (16+) on how meaningful they find their life's activities.

early_years_development

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).

feelings_of_anxiety

The average anxiety score of respondents (16+) when asked how they felt the day before.

happiness

The average happiness score of respondents (16+) when asked how they felt the day before.

healthy_eating

The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.

high_blood_pressure

The percentage of people reporting high blood pressure (hypertension) - not based on GP records but survey responses.

household_overcrowding

The percentage of households considered overcrowded, based on a standard calculation comparing the number of required rooms to the actual number of rooms.

life_expectancy

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.

life_satisfaction

The average life satisfaction score of respondents aged 16 and over.

low_level_crime

The number of police-recorded low-level crimes per 1,000 people, with bicycle theft and shoplifting used as indicators of overall rates.

mental_health_conditions

The percentage of people reporting a mental health condition, such as depression or anxiety- not based on GP records but survey responses.

overweight_and_obesity_in_adults

The percentage of adults (18+) who are overweight or obese, based on self-reported height and weight in a survey.

overweight_and_obesity_in_children

The percentage of children in Reception (aged 4-5) and Year 6 (aged 10-11) who are overweight or obese.

physical_activity

The percentage of adults (19+) reporting physical activity of 150 minutes or more per week.

rough_sleeping

The number of people sleeping outdoors on a single night in October or November, per 100,000 residents.

smoking

The percentage of adults (18+) who currently smoke cigarettes.

unemployment

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.

young_ppl_edu_empl_appren

The percentage of 16 and 17-year-olds in sustained education, employment, or apprenticeships one year after key stage 4 (after school Year 11).

Source

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.


The Health Index for England (2015 and 2021)

Description

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.

Usage

hie_15_21

Format

A data frame with 614 rows and 6 variables:

area_name

The area the data was collected from.

year

The year data was collected.

feelings_of_anxiety

The average anxiety score of respondents (16+) when asked how they felt the day before.

happiness

The average happiness score of respondents (16+) when asked how they felt the day before.

healthy_eating

The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.

life_satisfaction

The average life satisfaction score of respondents aged 16 and over.

Source

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.


The Health Index for England (2021)

Description

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.

Usage

hie_2021

Format

A data frame with 307 rows and 21 variables:

area_name

The area the data was collected from.

region

Regional categorisation of areas.

year

The year data was collected.

activities_in_life_are_worthwhile

The average score of respondents (16+) on how meaningful they find their life's activities.

early_years_development

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).

feelings_of_anxiety

The average anxiety score of respondents (16+) when asked how they felt the day before.

happiness

The average happiness score of respondents (16+) when asked how they felt the day before.

healthy_eating

The percentage of adults (16+) who report eating five or more portions of fruit and vegetables on a 'usual day'.

high_blood_pressure

The percentage of people reporting high blood pressure (hypertension) - not based on GP records but survey responses.

household_overcrowding

The percentage of households considered overcrowded, based on a standard calculation comparing the number of required rooms to the actual number of rooms.

life_expectancy

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.

life_satisfaction

The average life satisfaction score of respondents aged 16 and over.

low_level_crime

The number of police-recorded low-level crimes per 1,000 people, with bicycle theft and shoplifting used as indicators of overall rates.

mental_health_conditions

The percentage of people reporting a mental health condition, such as depression or anxiety- not based on GP records but survey responses.

overweight_and_obesity_in_adults

The percentage of adults (18+) who are overweight or obese, based on self-reported height and weight in a survey.

overweight_and_obesity_in_children

The percentage of children in Reception (aged 4-5) and Year 6 (aged 10-11) who are overweight or obese.

physical_activity

The percentage of adults (19+) reporting physical activity of 150 minutes or more per week.

rough_sleeping

The number of people sleeping outdoors on a single night in October or November, per 100,000 residents.

smoking

The percentage of adults (18+) who currently smoke cigarettes.

unemployment

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.

young_ppl_edu_empl_appren

The percentage of 16 and 17-year-olds in sustained education, employment, or apprenticeships one year after key stage 4 (after school Year 11).

Source

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.


IC Training Data

Description

A dataset which contains real-world pre- and post-training test scores for Intercultural Communication trainees. Participants names were replaced with random names.

Usage

ic_training

Format

A data frame with 96 rows and 11 variables:

name

Random names created with randomName package

test

Defines whether a test was performed before or after training

communication

Level of confidence in communication with people from diverse cultural backgrounds

teamwork

Level of confidence in working with people from diverse cultural backgrounds

leadership

Level of confidence in leading people from diverse cultural backgrounds

communication2

Factorised 'communication' with levels "yes and "no"

teamwork2

Factorised 'teamwork' with levels "yes and "no"

leadership2

Factorised 'leadership' with levels "yes and "no"

communication3

Factorised 'communication' with levels "high", "medium", and "low"

teamwork3

Factorised 'teamwork' with levels "high", "medium", and "low"

leadership3

Factorised 'leadership' with levels "high", "medium", and "low"

Source

Research conducted at the University of Warwick (2018)


Install and update all R packages used in the book

Description

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.

Usage

install_r4np()

Details

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.

Value

Invisibly, a character vector with the names of all packages that are installed after the function has run.

Examples

## Not run: 
# Run this line of code to install or update all relevant packages
install_r4np()

## End(Not run)

Perform normality test for multiple variables at once

Description

This function performs a Shapiro-Wilk normality test on multiple variables in a dataframe. It returns the results in a tidy format.

Usage

ntest(df, cols)

Arguments

df

A dataframe containing the data to be tested. It can be supplied directly (ntest(df = mtcars, ...)) or piped into the function (mtcars |> ntest(...)).

cols

<tidy-select> The numeric variables to test for normality, written as unquoted column names, e.g. mpg or c(mpg, disp). Selection helpers such as starts_with() or where(is.numeric) also work.

Details

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.

Value

A tibble with one row per variable and the columns variable, statistic, p.value and method.

See Also

ntest_by() to run normality tests for grouped data

Other assumption tests: ntest_by(), vtest()

Examples

# Test a single variable
ntest(df = mtcars, cols = mpg)

# Test several variables, piping the data into the function
mtcars |> ntest(c(mpg, disp, hp))

Perform normality test for multiple variables by groups

Description

This function performs a Shapiro-Wilk normality test on multiple variables in a dataframe by groups.

Usage

ntest_by(df, cols, group)

Arguments

df

A dataframe containing the data to be tested. It can be supplied directly (ntest_by(df = mtcars, ...)) or piped into the function (mtcars |> ntest_by(...)).

cols

<tidy-select> The numeric variables to test for normality, written as unquoted column names, e.g. mpg or c(mpg, disp). Selection helpers such as starts_with() or where(is.numeric) also work. Grouping variables are never tested.

group

<tidy-select> The variable that defines the groups, written as an unquoted column name, e.g. cyl. If you select several variables, e.g. c(gender, country), every combination of their values is treated as a separate group, so you get one test for each gender in each country.

Details

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).

Value

A tibble with one row per group and variable, containing the grouping variable(s) and the columns variable, statistic, p.value and method.

See Also

ntest() to run normality tests for ungrouped data

Other assumption tests: ntest(), vtest()

Examples

# 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))

People and Nature Survey for England, 2020-2023

Description

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.

Usage

pplnat

Format

A data frame with 3585 rows and 19 variables:

region

Different regions in England where data was collected.

wave

Data was collected in several waves. This provides opportunities to analyse data over time.

time_in_green

Item: In the last 12 months, how often, on average have you spent free time outside in green and natural spaces?

ncs_easy_walking_distance

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").

ncs_relax_unwind

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").

ncs_high_enough_standard

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").

imp_protect_environment

Item: How important is protecting the environment to you personally? | 1 ("Not at all important") to 5 = ("Very important").

concerned_damaging_environment

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").

pick_up_litter

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").

vote_political_party

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").

change_lifestyle

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)?

wb_lonely

Item: How often do you feel lonely? | 1 ("Never") to 5 = ("Often / always").

wb_satisfied

Item: Overall, how satisfied are you with your life nowadays? | 1 ("Not at all") to 10 = ("Completely").

wb_worthwhile

Item: Overall, how worthwhile are the things you do in your life? | 1 ("Not at all") to 10 = ("Completely").

wb_happy

Item: How happy were you feeling yesterday? | 1 ("Not at all") to 10 = ("Completely").

wb_worried_anxious

Item: How anxious were you feeling yesterday? | 1 ("Not at all") to 10 = ("Completely").

wb_worried_anxious_r

This is the reverse-scored item for wb_worried_anxious.

ncs

Natural connectedness scale (latent variable based on ncs items). A higher score implies higher natural connectedness.

wellbeing

Wellbeing (latent variable based on wb items). A higher score implies higher wellbeing

Source

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


Start and end dates/times of a questionnaire

Description

A dataset which contains start and end dates regarding the completion of a questionnaire.

Usage

quest_time

Format

A data frame with 84 rows and 3 variables:

id

Unique identifier of participant

start

The date and time at which a participant started the questionnaire

end

The date and time at which a participant finished the questionnaire

Source

A random selection of observations from the Global Education Profiler (GEP).


Student Reading Time

Description

This dataset contains English comments by students about their study experiences at a fictitious university.

Usage

reading_time

Format

A data frame with 209 rows and 3 variable:

gender

Gender of the participant

degree_level

Degree level of participant

min_reading

Reading time per week measured in minutes

Source

Fictitious dataset created for educational purposes.


Simpson's Paradox: A demonstration dataset (random sample)

Description

A dataset to demonstrate the Simpson's Paradox.

Usage

simpson

Format

A data frame with 300 rows and 3 variables:

performance

Student's change in performance at school.

happiness

Participant's change in happiness

group

Group a participant belongs to, i.e. Teacher, Student, or Parent

Source

Dataset created with correlation::simulate_simpson()


Salary, Work experience, and Mindfulness (SWM)

Description

This dataset contains information about employees' salary, their working experience and time spend on mindfulness practices.

Usage

swm

Format

A data frame with 100 rows and 3 variables:

salary

Salary earned (in USD 1000)

work_experience

Years of working experience

mindfulness

Minutes spent on mindfulness practices in a 5-day working week.

Source

Fictitious dataset created for educational purposes.


Test homogeneity of variance for multiple variables at once

Description

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.

Usage

vtest(df, cols, group, center = c("median", "mean"))

Arguments

df

A dataframe containing the data to be tested. It can be supplied directly (vtest(df = mtcars, ...)) or piped into the function (mtcars |> vtest(...)).

cols

<tidy-select> The numeric variables to test, written as unquoted column names, e.g. mpg or c(mpg, disp). Selection helpers such as starts_with() or where(is.numeric) also work. Grouping variables are never tested.

group

<tidy-select> The variable that defines the groups to compare, written as an unquoted column name, e.g. cyl. If you select several variables, e.g. c(cyl, am), every combination of their values is treated as a separate group, as needed for a factorial (e.g. two-way) ANOVA.

center

The value each group is centred on: "median" (the default) or "mean". "median" is the default in car::leveneTest() and is more robust when the data are not normally distributed (it is also known as the Brown-Forsythe test). "mean" gives the original Levene's test, which is what SPSS reports.

Details

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).

Value

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.

See Also

ntest() and ntest_by() to test the assumption of normality

Other assumption tests: ntest(), ntest_by()

Examples

# 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))

World Value Survey (Extract)

Description

A dataset which contains selected data from the World Value Survey. This data was obtained in October 2020.

Usage

wvs

Format

A data frame with 8564 rows and 7 variables:

Participant ID

Unique identifier for each participant

Country name

Country name, partially abbreviated

Gender

Gender of participant

Age

Age of participant at the time of data collection

relationship_status

Relationship status of participants

Freedom.of.Choice

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").

Satisfaction-with-life

Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)

Source

World Value Survey (WVS) (https://www.worldvaluessurvey.org)


World Value Survey (Extract)

Description

A cleaned version of the wvs dataset.

Usage

wvs_nona

Format

A data frame with 8564 rows and 6 variables:

country

Country name, partially abbreviated

gender

Gender of participant

age

Age of participant at the time of data collection

relationship_status

Relationship status of participants

freedom_of_choice

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").

satisfaction

Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)

Source

World Value Survey (WVS) (https://www.worldvaluessurvey.org)


World Value Survey (Waves)

Description

A dataset excerpt from the World Value Survey including 3 countries over 7 waves of data collection.

Usage

wvs_waves

Format

A data frame with 2100 rows and 5 variables:

id

Unique ID for each participant

wave

Random names created with randomName package

country

Defines whether a test was performed before or after training

satisfaction

Item: All things considered, how satisfied are you with your life as a whole these days? | 1 (“completely dissatisfied”) to 10 (“completely satisfied”)

freedom_of_choice

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").

Source

World Value Survey (WVS). Data retrieve from https://www.worldvaluessurvey.org