if (!require("pacman")) install.packages("pacman")
library(pacman)
p_load(
tidyverse, jsonlite, qualtRics, sjlabelled, hms, openxlsx, scales, qualtRics, here
)
knitr::opts_knit$set(root.dir = "../")
set.seed(8675309)3 Generate Synthetic Data
This file is deprecated. It previously synthetically sampled from real data, with PII and thus internal only, and saved it’s outputs to data/data-synthetic-raw. These files are fixed and this no longer needs to be run, but is saved for posterity to have a record of the data generating process.
3.1 Libraries
First, load some libraries we’ll need.
These are some functions we’ll need—to generate a random time in HH:MM format, to assign genres to games, and to sample from a zero-inflated gamma distribution.
# Function to generate a random time in hh:mm format
randomTime <- function(n) {
randomHours <- runif(n, 0, 24)
randomMinutes <- runif(n, 0, 60)
randomTimes <- now() + dhours(randomHours) + dminutes(randomMinutes)
format(randomTimes, "%H:%M")
}
# Function to randomly assign 1-3 genres to a game
assignGenres <- function(genres) {
numGenres <- sample(1:3, 1, prob = c(.5, .3, .2))
genres <- sample(genres, numGenres, replace = FALSE)
paste(genres, collapse = ", ")
}
# function to sample from a zero-inflated gamma distribution, used for iOS app categories
sampleTime <- function(n) {
ifelse(runif(n) < 0.4, 0, rgamma(n, shape = 3, scale = 2 / 2))
}
# Sample a single row from df_source based on a matching ID
sampleRowByID <- function(id, df, nRows) {
df |>
filter(ID == !!id) |> # Filter rows that match the given ID
slice_sample(n = nRows, replace = FALSE) # Randomly sample one row
}Then, import the true data we need, from which we’ll do some bootstrapping. This is found in data/data-template.
datSurvey <- read_csv("data/data-template/survey.csv.gz")
datNintendo <- read_csv("data/data-template/telemetry.csv.gz")
datDemo <- read_csv("data/data-template/demographics.csv.gz")
datMeta <- read_csv("data/data-template/gameMetadata.csv.gz")
datXbox <- read.delim("data/data-template/xbox.txt")
datSteam <- read_csv("data/data-template/steam.csv.gz") |>
filter(played == "Yes")
datAndroid <- fromJSON("data/data-template/android.json")
datIntake <- read_survey("data/data-template/intake.csv.gz") |>
filter(consent == "Yes, I agree to take part") |>
dplyr::select(-(StartDate:consent), -(isWilling:RANDOM_ID), -c(gender_4_TEXT, localDatetime, gender, employment)) |>
mutate(playProp_7 = "") # fix one broken column
datPanelRaw <- read_survey("data/data-template/panel.csv.gz")
datPanel <- datPanelRaw |>
dplyr::select(-c(StartDate:UserLanguage), -PID, -wave) |>
# test responses for mctq don't work at all so we need to fill these in manually
mutate(
mctq_2_1 = sample(0:7, n(), replace = TRUE, prob = c(.05, .05, .10, .10, .20, .25, .15, .10)),
across(c(mctq_6_6, mctq_6_4, mctq_3_6, mctq_3_4), ~ runif(n(), min = 1, max = 60)),
across(c(mctq_3_1, mctq_3_3, mctq_3_5, mctq_6_1, mctq_6_3, mctq_6_5), ~ randomTime(n()))
) |>
# Reapply the original labels to ensure they are retained
copy_labels(datPanelRaw)
datDiary <- read_survey("data/data-template/diary.csv.gz") |>
dplyr::select(-c(StartDate:UserLanguage), -PID, -wave)Set up basic parameters of the data simulation.
set.seed(8675309)
n <- 2000
diaryWaves <- 30
panelWaves <- 6
studyStartDate <- as_datetime("2024-05-01 00:00:00")
studyDays <- (panelWaves-1) * 14 + 1
studyDates <- ymd(studyStartDate + days(0:studyDays))3.2 Simulate participant sample
First we simulate the sample as taken - their age, gender, region, and gameplay tendencies. We bootstrap from existing Nintendo pilot data, but add some demographic details that are not present in the Prolific data. This takes the format of the intake questionnaire on Qualtrics, and therefore needs to import that survey.
We also simulate the gameplay behavior of participants - what platforms do they play on, and how frequently do they play on each of them.
Participant platforms don’t match the responses in the platforms_X intake items, as these are generated from Qualtrics test responses. We have a better idea of the platform distribution so we simulate that ourselves.
3.2.1 Intake
synIntake <- tibble(
pid = as.character(1:n),
region = rep(c("US", "UK"), n / 2)
) |>
# bootstrap each column from the non-NA values in the original data
cbind(map_dfc(datIntake, ~ rep(sample(.[!is.na(.)], length(.), replace = TRUE), length.out = n))) |>
# for a handful of relevant columns, we override the generate test response
# distributions with custom ones
mutate(
age = ifelse(region == "US",
sample(18:30, n, replace = TRUE),
sample(18:75, n, replace = TRUE)
),
sex = sample(datDemo$sexProlific[!is.na(datDemo$sexProlific)],
n(),
replace = TRUE
),
employment = sample(
datDemo$employmentStatusProlific[!is.na(datDemo$employmentStatusProlific) &
datDemo$employmentStatusProlific != "DATA_EXPIRED"],
n(),
replace = TRUE
),
eduLevel = sample(datSurvey$eduLevel[!is.na(datSurvey$eduLevel)], n(), replace = TRUE),
ethnicity = sample(datDemo$ethnicity[!is.na(datDemo$ethnicity)], n(), replace = TRUE),
height = ifelse(sex == "Male",
round(rnorm(n(), 69, 3)),
round(rnorm(n(), 64, 3))
),
weight = ifelse(sex == "Male",
round(rnorm(n(), 190, 35)),
round(rnorm(n(), 160, 35))
),
localTimeZone = sample(datDemo$localTimeZone[!is.na(datDemo$localTimeZone)], n(), replace = TRUE)
) |>
# convert height into feet and inches
mutate(
`height#1_1_1` = height %% 12,
`height#1_1_2` = height %/% 12,
.keep = "unused"
) |>
# add gaming characteristics
mutate(
playsSwitch = sample(c(TRUE, FALSE), n(), prob = c(.4, .6), replace = TRUE),
playsXbox = sample(c(TRUE, FALSE), n(), prob = c(.5, .5), replace = TRUE),
playsSteam = ifelse(region == "US",
sample(c(TRUE, FALSE), n(), prob = c(.5, .5), replace = TRUE),
FALSE
),
playsSteam = ifelse(!playsSwitch & !playsXbox & !playsSteam, TRUE, playsSteam), # so that all players play on at least one platform
# for people who play on a given platform, how likely are they to play on a particular day, using beta distribution
dailyNintendoPlayLikelihood = ifelse(playsSwitch, rbeta(n(), 2, 8), 0),
dailyXboxPlayLikelihood = ifelse(playsXbox, rbeta(n(), 3, 5), 0),
dailySteamPlayLikelihood = ifelse(playsSteam, rbeta(n(), 3, 5), 0),
iOSuser = sample(c(TRUE, FALSE), n(), prob = c(.7, .3), replace = TRUE),
androidUser = !iOSuser
) |>
copy_labels(datIntake)3.2.2 Play History
Next, we want to simulate some play behavior. We assume that each player has a fixed likelihood of playing on each platform they use on a given day. If they do play, we assume they will play between 1 and 3 sessions (or in the case of Steam, that they have logged playtime in 1-5 1-hour periods of the day). We simulate those values here.
synPlayHistory <- synIntake |>
crossing(day = 1:studyDays) |>
mutate(date = studyDates[day]) |>
select(pid, day, date, starts_with(c("plays", "daily"))) |>
rowwise() |>
mutate(
numSessionsNintendo = ifelse(runif(n()) < dailyNintendoPlayLikelihood,
sample(1:3, 1, prob = c(.7, .2, .1)),
0
),
numSessionsXbox = ifelse(runif(n()) < dailyXboxPlayLikelihood,
sample(1:3, 1, prob = c(.7, .2, .1)),
0
),
numHoursWithSteamPlay = ifelse(runif(n()) < dailySteamPlayLikelihood,
sample(1:5, 1, prob = c(.4, .25, .2, .1, .05)),
0
),
)3.2.3 Dropout/attrition
Here, we simulate the properties of participant dropout. We assume that participants have a base rate of missingness at each wave (5% for diary, 10% for panel), and a separate chance each day of dropping out for the rest of the study (1% for the 84 days of the study). We simulate the missingness and dropout for each participant for each day of the study, and use this information later to remove rows from the completed panel and diary surveys.
dropout <- expand.grid(pid = 1:n, day = 1:studyDays) |>
# first define the various time components of the study
mutate(
diaryWave = ifelse(day <= 30, day, NA),
week = ceiling(day / 7),
panelWave = ifelse((day - 1) %% 14 == 0, (day - 1) %/% 14 + 1, NA) # return 1 on day 1, 2 on day 15, 3 on day 29, etc
) |>
arrange(as.integer(pid), day) |>
# for simplicity, first we simulate dropout for every day of the study, then only keep the missingness on relevant days
mutate(
missingDiary = sample(c(TRUE, FALSE), n(), replace = TRUE, prob = c(.05, .5)),
missingPanel = sample(c(TRUE, FALSE), n(), replace = TRUE, prob = c(.1, .9)),
dropout = sample(c(TRUE, FALSE), n(), replace = TRUE, prob = c(.01, .99))
) |>
mutate(
missingPanel = ifelse(is.na(panelWave), NA, missingPanel),
missingDiary = ifelse(is.na(diaryWave), NA, missingDiary)
) |>
group_by(pid) |>
mutate(
missingPanel = ifelse(cumsum(dropout) > 0, TRUE, missingPanel),
missingDiary = ifelse(cumsum(dropout) > 0, TRUE, missingDiary)
) |>
# clean up
ungroup() |>
mutate(pid = as_character(pid))3.3 Simulate Telemetry
First we quickly generate a list of unique genres, which we will later randomly assign to games. In the real study, we will match games on all platforms to these same categories using the IGDB database.
3.3.1 Genres
# We pull from the genres present in the Nintendo metadata (which were in turn pulled from IGDB)
uniqueGenres <- datMeta |>
filter(!is.na(genres)) |> # Remove NAs
separate_rows(genres, sep = ",") |> # Split by comma
distinct(genres) |> # Get unique genres
pull(genres) |>
sort()3.3.2 Nintendo
Next, we simulate the session-level data based on the play behavior, starting with Nintendo. For each day and session that a participant has played, we bootstrap the title, start time, and duration, from the existing data. For example, Participant 14 played Switch on Day 11, and their play was simulated to include 2 unique sessions. Games, session start times, and session durations are all drawn randomly from the real Nintendo data.
synNintendo <- synPlayHistory |>
filter(numSessionsNintendo > 0) |>
mutate(session = list(1:numSessionsNintendo)) |>
unnest(session) |>
mutate(
titleID = sample(datNintendo$titleID, n(), replace = TRUE),
sessionStart = date + seconds(runif(n(), 0, 86400)),
duration = sample(datNintendo$duration, n(), replace = TRUE),
sessionEnd = sessionStart + minutes(as.integer(duration)),
genre = replicate(n(), assignGenres(uniqueGenres)),
) |>
select(-(playsSwitch:numHoursWithSteamPlay)) |>
mutate(platform = "Nintendo")
glimpse(synNintendo)3.3.3 Xbox
We take a similar approach for the Xbox data. However, instead of bootstrapping, we instead randomly pull from a list of an external list of Xbox games. We pull session start times from the Nintendo dataset as these are probably an equally good representation, but simulate a new set of durations as the average Xbox session is likely longer than Nintendo.
xboxGames <- read_csv("https://github.com/ItsLogic/Xbox-TitleIDs/raw/main/IDs.csv")[1:300, ]
synXbox <- synPlayHistory |>
filter(numSessionsXbox > 0) |>
mutate(session = list(1:numSessionsXbox)) |>
unnest(session) |>
mutate(
titleID = sample(xboxGames$`Game Title`, n(), replace = TRUE),
sessionStart = date + seconds(runif(n(), 0, 86400)),
duration = round(rgamma(n(), shape = 2, rate = 1) * 60, 2),
sessionEnd = sessionStart + minutes(as.integer(duration)),
genre = replicate(n(), assignGenres(uniqueGenres))
) |>
select(-(playsSwitch:numHoursWithSteamPlay)) |>
mutate(platform = "Xbox")
glimpse(synXbox)3.3.4 Steam
Next, we move to Steam data. Here we use an existing sample of Steam data as output by Gameplay.Science (hosted on OneDrive, path specified in .Renviron).
In contrast to Xbox and Nintendo data, Steam data is not session-level; rather, it is a total amount of time spent playing each game during the previous hour. We simulate this by looking if the person played that day, simulating a random number of hours between 1-5 that they may have played, and then filling in an amount of time for each hour of play.
We also randomly assign genres to each game, as we did for Nintendo and Xbox.
# note that the code structure of the steam sim is a little different, as it derives from a different process (using LLMs to generate user personas)
steam <- read_csv(Sys.getenv("steamDataPath")) |>
filter(played == "Yes")
# with more realistic numbers of sessions per player, the loop iteration was getting prohibitively slow
# so we assign a random persona for each observation in synPlayHistory, then suse sampleRowByID() to only sample rows from steam
# where the ID matches. This is much faster, with the only downside being that different days may have identical sessions,
# but I don't see this as a problem for the purposes of the sim (and in fact this might have been happening before anyway?)
synSteam <- synPlayHistory |>
mutate(persona = sample(unique(steam$ID), n(), replace = TRUE)) |> # assign random persona
filter(numHoursWithSteamPlay > 0) |> # for each day where steam play occurs
mutate(
sampled_row = list(sampleRowByID(persona, steam, numHoursWithSteamPlay)) # sample a certain number of hour-sessions from that persona
) |>
unnest(cols = c(sampled_row)) |>
# clean up
dplyr::select(pid, day, date, hour = time, everything(), -(playsSwitch:numHoursWithSteamPlay), -ID, -played) |>
# add some columns to match the format of the other datasets
mutate(
sessionStart = as.POSIXct(paste(date, hour), format = "%Y-%m-%d %H"),
sessionEnd = sessionStart+minutes(as.integer(minutes))
) |>
arrange(as.integer(pid), day, date, hour) |>
mutate(platform = "Steam")
glimpse(synSteam)3.3.5 iOS
iOS data consists of weekly screen time data for the below categories (pre-defined by Apple). We simulate the value of each of these categories for each participant-week using a zero-inflated gamma distribution, then add dropout as before.
appCategories <- c(
"Entertainment", "Social", "Information & Reading", "Games", "Productivity & Finance", "Travel", "Other",
"Creativity", "Education", "Health & Fitness", "Shopping & Food", "Utilities"
)
syniOS <- expand.grid(
pid = synIntake$pid[synIntake$iOSuser],
week = 1:(panelWaves * 2),
category = appCategories
) |>
mutate(
duration = sampleTime(n()),
date = studyDates[week * 7 - 6]
) |>
pivot_wider(names_from = category, values_from = duration, values_fill = 0) %>%
mutate(totalScreentime = rowSums(select(., -c(pid, week, date)))) |>
mutate(
missing = sample(c(TRUE, FALSE), n(), replace = TRUE, prob = c(.1, .9)),
dropout = sample(c(TRUE, FALSE), n(), replace = TRUE, prob = c(.01, .99))
) |>
group_by(pid) |>
mutate(missing = ifelse(cumsum(dropout) > 0, TRUE, missing)) |>
ungroup() |>
select(pid, week, date, missing, dropout, everything()) |>
mutate(across(-c(pid, week, missing, dropout), ~ if_else(missing | dropout, NA, .))) |>
arrange(as.integer(pid), week) |> mutate(platform = "iOS")
glimpse(syniOS)3.3.6 Android
Last, we simulate android data, bootstrapping from a sample ActivityWatch output (hosted on OneDrive, path specified in .Renviron).
# Extract and normalize the 'events' data - app sessions - which are found in the 'aw-watcher-android-test' bucket
androidEvents <- datAndroid$buckets$`aw-watcher-android-test`$events |>
as_tibble() |>
flatten()
synAndroid <- expand.grid(
pid = synIntake$pid[synIntake$androidUser],
day = 1:studyDays
) |>
mutate(
numDailyAppSessions = round(rgamma(n(), 10, .5)),
date = studyDates[day]
) |> # simulate a random number of app sessions to have taken place that day
rowwise() |>
mutate(session = list(1:numDailyAppSessions)) |>
unnest(session) |>
mutate(
app = sample(androidEvents$data.app, n(), replace = TRUE), ,
sessionStart = sample(ymd_hms(androidEvents$timestamp), n(), replace = TRUE),
sessionStart = as.period(as_hms(sessionStart)),
duration = sample(androidEvents$duration, n(), replace = TRUE),
sessionEnd = sessionStart + minutes(as.integer(duration)),
) |>
# for simplicity at the simulation stage, we simply random assign categories to each app, matching the iOS categories
# in the full paper, we will map apps to categories using the google play store API
group_by(app) |>
mutate(
category = sample(appCategories, 1, replace = TRUE),
genre = ifelse(category == "Games",
replicate(1, assignGenres(uniqueGenres)),
NA)
) |>
ungroup() |>
arrange(as.integer(pid), day, sessionStart) |> mutate(platform = "Android")
glimpse(synAndroid)3.4 Simulate self-report data (diary and panel)
We now move to the self-report data. For both surveys, the simplest option is to just use Qualtrics’ “generate test response” feature, then pull that data using the Qualtrics API, so that the simulated data accurately mirrors the structure of the data we will later have (if not the distributional properties).
We’ll want to add missingness and dropout to both the panel and diary data, which we do by adding a base chance of missingness at every wave, alongside a separate chance at each wave that the participant will drop out for the rest of the study. See above for details.
3.4.1 Panel
synPanel <- expand.grid(pid = as.character(1:n), wave = 1:panelWaves) |>
# add random completion time between 12pm and 12pm the following day
mutate(
date = studyDates[wave * 14 - 13],
surveyCompletionTime = date + seconds(runif(n(), 43200, 129600))
) |>
# bootstrap each column from the non-NA values in the original data
cbind(map_dfc(datPanel, ~ rep(sample(.[!is.na(.)], length(.), replace = TRUE), length.out = n * panelWaves))) |>
# Special transformation needs to be done to `psqi_4#1_1_1` and `psqi_4#1_1_2` columns to move values in normal range.
mutate(
`psqi_4#1_1_1` = rescale(`psqi_4#1_1_1`, to = c(0, 12), na.rm = TRUE),
`psqi_4#1_1_2` = rescale(`psqi_4#1_1_2`, to = c(0, 60), na.rm = TRUE)
) |>
# certain measures are only administered at certain waves, set these to 0 for
# the other waves
mutate(across(starts_with(c("BFI", "trojan", "mctq")), ~ ifelse(wave != 1, NA, .))) |>
mutate(across(starts_with("gdt"), ~ ifelse(wave %in% c(2:5), NA, .))) |>
mutate(across(starts_with(c("psqi", "eps")), ~ ifelse(wave %in% c(1, 3, 5), NA, .))) |>
# join with the relevant rows/cols of the missingness df
left_join(dropout |> filter(!is.na(panelWave)) |> select(pid, panelWave, missingPanel),
by = c("pid", "wave" = "panelWave")
) |>
select(pid, wave, date, missingPanel, everything()) |>
# remove data for all missing diary waves
mutate(across(-c(pid, wave, missingPanel), ~ if_else(missingPanel, NA, .))) |>
arrange(as.numeric(pid), wave) |>
copy_labels(datPanel)Click to view the structure of the panel data
glimpse(synPanel)3.4.2 Diary
synDiary <- expand.grid(pid = synIntake$pid[synIntake$region == "US"], day = 1:diaryWaves) |>
mutate(
date = studyDates[day],
surveyCompletionTime = date + seconds(runif(n(), 64800, 93600)) # add time so that the survey is randomly completed between 6pm and 2am
) |>
# bootstrap each column from the non-NA values in the original data
cbind(map_dfc(datDiary, ~ rep(sample(.[!is.na(.)], length(.), replace = TRUE),
length.out = length(synIntake$pid[synIntake$region == "US"]) * diaryWaves
))) |>
# join with missingness df
left_join(dropout |> filter(!is.na(diaryWave)) |> select(pid, diaryWave, missingDiary),
by = c("pid", "day" = "diaryWave")
) |>
# remove data for all missing diary waves, and removing gaming data when the
# participant didn't play in the last 24 hours
mutate(
across(-c(pid, day, date, missingDiary), ~ if_else(missingDiary, NA, .)),
across(starts_with(c("socialGaming", "bangs", "mostRecentGame", "displaced")), ~ ifelse(played24hr == "No", NA, .)) # remove gaming data
) |>
# clean up
select(pid, day, date, missingDiary, everything()) |>
arrange(as.integer(pid), day) |>
copy_labels(datDiary)Click to view the structure of the diary data
glimpse(synDiary)3.5 Generate Codebook
Generate codebook.xlsx.
metaInfo <- tribble(
~Tab, ~`Data File`, ~Content,
"Intake", "data-synthetic/synIntake.csv.gz", "Data on participant demographics and gaming habits",
"Panel", "data-synthetic/synPanel.csv.gz", "Wellbeing, sleep and time use data from the panel survey",
"Diary", "data-synthetic/synDiary.csv.gz", "Daily diary data on gaming, wellbeing, and sleep",
"Nintendo", "data-synthetic/synNintendo.csv.gz", "Telemetry data (session-level) from the Nintendo Switch",
"Xbox", "data-synthetic/synXbox.csv.gz", "Telemetry data (session-level) from Xbox devices",
"Steam", "data-synthetic/synSteam.csv.gz", "Telemetry data (total playtime in 1 hour blocks) from Steam",
"iOS", "data-synthetic/syniOS.csv.gz", "Screen time data from iOS devices, pulled from screenshots of the Screen time app",
"Android", "data-synthetic/synAndroid.csv.gz", "App usage data from Android devices, pulled from ActivityWatch"
)
intakeCodebook <- synIntake |>
get_label() |>
enframe() |>
separate(value, into = c("stem", "item"), sep = " - ", extra = "merge", fill = "right", remove = FALSE) |>
mutate(
Item = if_else(is.na(item), value, item),
`Stem text` = if_else(grepl(" - ", value), stem, NA),
.keep = "unused"
)
panelCodebook <- synPanel |>
get_label() |>
enframe() |>
separate(value, into = c("stem", "item"), sep = " - ", extra = "drop", fill = "right", remove = FALSE) |>
mutate(
Item = if_else(is.na(item), value, item),
`Stem text` = if_else(grepl(" - ", value), stem, NA),
.keep = "unused"
) |>
mutate(
Source = case_when(
grepl("wemwbs", name) ~ "Warwick-Edinburgh Mental Wellbeing Scale (https://doi.org/10.1186/1477-7525-5-63)",
grepl("promis", name) ~ "PROMIS Short Form 8a Adult Depression Scale (https://doi.org/10.1177/1073191111411667)",
grepl("bangs", name) ~ "Basic Needs in Games Scale (https://doi.org/10.31234/osf.io/4965z7)",
grepl("trojan", name) ~ "Trojan Player Typology (https://doi.org/10.1016/j.chb.2015.03.018)",
grepl("gdt", name) ~ "Gaming Disorder Test (https://doi.org/10.1007/s11469-019-00088-z)",
grepl("mctq", name) ~ "Munich Chronotype Questionnaire (https://doi.org/10.1177/0748730402239679)",
grepl("pqsi", name) ~ "Pittsburgh Sleep Quality Index (https://doi.org/10.1016/0165-1781(89)90047-4)",
grepl("eps", name) ~ "Epwoth Sleepiness Scale (https://doi.org/10.1093/sleep/14.6.540)",
grepl("BFI", name) ~ "Extra-short Big Five Inventory–2 (https://doi.org/10.1016/j.jrp.2017.02.004)",
grepl("lifeSat", name) ~ "Cantril Self-anchoring Scale (Cantril, 1965)",
TRUE ~ ""
),
`Response Options` = case_when(
grepl("wemwbs", name) ~ "1 - None of the time; 2 - Rarely; 3 - Some of the time; 4 - Often; 5 - All of the time",
grepl("promis", name) ~ "Never; Rarely; Sometimes; Often; Never",
grepl("bangs", name) ~ "1 Strongly Disagree; 2; 3; 4 Neither Agree nor Disagree; 5; 6; 7 Strongly Agree",
grepl("trojan", name) ~ "1 - Strongly disagree; 2; 3; 4; 5 - Strongly agree",
name %in% c("problematicPlay", "positives") ~ "free text response",
grepl("displacement", name) ~ "Greatly interfered; Moderately interfered; Slightly interfered; No impact; Slightly supported;
Moderately supported; Greatly supported",
grepl("timeUse", name) ~ "slider from 0-16 hours, with increments of .1",
grepl("eps", name) ~ "No chance of dozing; Slight chance of dozing; Moderate chance of dozing; High chance of dozing",
grepl("BFI", name) ~ "Disagree strongly; Disagree a little; Neutral, no opinion; Agree a little; Agree strongly",
grepl("lifeSat", name) ~ "1-100 sliding scale",
TRUE ~ ""
),
`Stem text` = gsub("[\r\n]", "", `Stem text`)
) |>
rename(Variable = name)
diaryCodebook <- synDiary |>
get_label() |>
enframe() |>
separate(value, into = c("stem", "item"), sep = " - ", extra = "drop", fill = "right", remove = FALSE) |>
mutate(
Item = if_else(is.na(item), value, item),
`Stem text` = if_else(grepl(" - ", value), stem, NA),
.keep = "unused"
) |>
mutate(
Source = case_when(
grepl("bangs", name) ~ "Basic Needs in Games Scale (https://doi.org/10.31234/osf.io/4965z7)",
grepl("bpnsfs", name) ~ "Basic Psychological Need Satisfaction and Frustration Scale (https://doi.org/10.1007/s11031-014-9450-1), brief version (https://doi.org/1015-5759/a000846)",
grepl("stress|howStress", name) ~ "Daily Inventory of Stressful Events (https://doi.org/10.1177/1073191102091006)",
grepl("sd_", name) ~ "Consensus Sleep Diary (https://doi.org/10.5665/sleep.1642)",
grepl("lifeSat", name) ~ "Cantril Self-anchoring Scale (Cantril, 1965)",
TRUE ~ ""
),
`Response Options` = case_when(
grepl("bangs", name) ~ paste(names(table(synDiary$bangs_1)), collapse = "; "),
grepl("bpnsfs", name) ~ paste(names(table(synDiary$bpnsfs_1)), collapse = "; "),
grepl("timeUse", name) ~ "slider from 0-16 hours, with increments of .1",
grepl("^stress", name) ~ "Yes; No",
grepl("howStress", name) ~ "Not at all; Not very; Somewhat; Very",
name == "sd_0" ~ "Regular work day; Regular day off; Weekend; Holiday; Vacation day Other (please specify):",
grepl("lifeSat", name) ~ "1-100 sliding scale",
TRUE ~ ""
),
`Stem text` = gsub("[\r\n]", "", `Stem text`)
) |>
rename(Variable = name)
nintendoCodebook <- synNintendo |>
var_labels(
pid = "A unique identifier assigned to each participant in the study.",
day = "The day number relative to the start of the study (e.g., Day 1, Day 2).",
date = "The calendar date on which the gaming session occurred (format: YYYY-MM-DD).",
session = "A sequential identifier for each gaming session on a given day for the participant.",
titleID = "The name of the game played during the session.",
sessionStart = "The time of day when the gaming session began (format: HH:MM:SS).",
duration = "The length of the gaming session in minutes.",
genre = "The genre(s) of the game played (e.g., Action, Puzzle, Role-Playing), using IGDB categories.",
platform = "The platform on which the game was played, for use in future merging (here: always Nintendo)."
) |>
get_label() |>
enframe(name = "Variable", value = "Description") |>
mutate(Notes = case_when(
Variable == "genre" ~ paste0("Possible genres are: ", paste(uniqueGenres, collapse = ", ")),
TRUE ~ ""
))
xboxCodebook <- synXbox |>
var_labels(
pid = "A unique identifier assigned to each participant in the study.",
day = "The day number relative to the start of the study (e.g., Day 1, Day 2).",
date = "The calendar date on which the gaming session occurred (format: YYYY-MM-DD).",
session = "A sequential identifier for each gaming session on a given day for the participant.",
titleID = "The name of the game played during the session.",
sessionStart = "The time of day when the gaming session began (format: HH:MM:SS).",
duration = "The length of the gaming session in minutes.",
genre = "The genre(s) of the game played using IGDB categories.",
platform = "The platform on which the game was played, for use in future merging (here: always Xbox)."
) |>
get_label() |>
enframe(name = "Variable", value = "Description") |>
mutate(Notes = case_when(
Variable == "genre" ~ paste0("Possible genres are: ", paste(uniqueGenres, collapse = ", ")),
TRUE ~ ""
))
steamCodebook <- synSteam |>
var_labels(
pid = "A unique identifier assigned to each participant in the study.",
day = "The day number relative to the start of the study (e.g., Day 1, Day 2).",
date = "The calendar date on which the gaming session occurred (format: YYYY-MM-DD).",
hour = "The hour of the day when the gaming session began (0-23).",
persona = "One of 250 possible Steam personas, generated by LLMs, with particular gameplay habits",
genre = "The genre(s) of the game played using IGDB categories.",
minutes = "The number of minutes played of that game during the hour period in question.",
AppID = "A unique identifier assigned to each game on the Steam platform.",
Name = "The name of the game played during the session.",
platform = "The platform on which the game was played, for use in future merging (here: always Steam)."
) |>
get_label() |>
enframe(name = "Variable", value = "Description") |>
mutate(Notes = case_when(
Variable == "genre" ~ paste0("Possible genres are: ", paste(uniqueGenres, collapse = ", ")),
TRUE ~ ""
))
iOSCodebook <- syniOS |>
var_labels(
missing = "Indicator for whether the data for the week is missing (TRUE = missing).",
dropout = "Indicator for whether the participant dropped out of the study (TRUE = dropped out).",
pid = "A unique identifier assigned to each participant in the study.",
week = "The week number relative to the start of the study.",
date = "The date corresponding to the start of the week in question (format: YYYY-MM-DD).",
Entertainment = "Total amount of time spent in entertainment apps during the week (in minutes).",
Social = "Total amount of time spent in social media apps during the week (in minutes).",
`Information & Reading` = "Total amount of time spent in information and reading apps during the week (in minutes).",
Games = "Total amount of time spent in gaming apps during the week (in minutes).",
`Productivity & Finance` = "Total amount of time spent in productivity and finance apps during the week (in minutes).",
Travel = "Total amount of time spent in travel-related apps during the week (in minutes).",
Other = "Total amount of time spent in other uncategorized apps during the week (in minutes).",
Creativity = "Total amount of time spent in creativity apps (e.g., photo/video editing) during the week (in minutes).",
Education = "Total amount of time spent in educational apps during the week (in minutes).",
`Health & Fitness` = "Total amount of time spent in health and fitness apps during the week (in minutes).",
`Shopping & Food` = "Total amount of time spent in shopping and food-related apps during the week (in minutes).",
Utilities = "Total amount of time spent in utility apps (e.g., weather, calculators) during the week (in minutes).",
totalScreentime = "Total amount of screen time across all app categories during the week (in minutes)."
) |>
get_label() |>
enframe(name = "Variable", value = "Description")
androidCodebook <- synAndroid |>
var_labels(
pid = "A unique identifier assigned to each participant in the study.",
day = "The day number relative to the start of the study (e.g., Day 1, Day 2).",
numDailyAppSessions = "The total number of app sessions recorded on the given day.",
date = "The calendar date on which the app sessions occurred (format: YYYY-MM-DD).",
session = "A sequential identifier for each app session on the given day for the participant.",
app = "The name of the app used during the session.",
sessionStart = "The time of day when the app session began (format: HH:MM:SS).",
duration = "The duration of the app session in minutes.",
category = "The category of the app used during the session (e.g., Social, Productivity, Entertainment)."
) |>
get_label() |>
enframe(name = "Variable", value = "Description")
# Generate and format codebook
write.xlsx(
list(
"Meta-info" = metaInfo,
"Intake" = intakeCodebook,
"Panel" = panelCodebook,
"Diary" = diaryCodebook,
"Nintendo" = nintendoCodebook,
"Xbox" = xboxCodebook,
"Steam" = steamCodebook,
"iOS" = iOSCodebook,
"Android" = androidCodebook
),
file = "codebook.xlsx",
headerStyle = createStyle(textDecoration = "bold", halign = "center"),
overwrite = TRUE,
colWidths = "auto"
)
codebook <- loadWorkbook("codebook.xlsx")
addStyle(codebook, "Meta-info", rows = nrow(metaInfo) + 3, cols = 1:3, style = createStyle(wrapText = TRUE))
setColWidths(codebook, "Intake", cols = 1:3, widths = c(25, 100, 40))
setColWidths(codebook, "Panel", cols = 1:3, widths = c(25, 100, 40))
setColWidths(codebook, "Diary", cols = 1:3, widths = c(25, 100, 40))
addStyle(codebook, "Intake", rows = nrow(intakeCodebook) + 3, cols = 1:3, style = createStyle(wrapText = TRUE))
addStyle(codebook, "Panel", rows = nrow(panelCodebook) + 3, cols = 1:3, style = createStyle(wrapText = TRUE))
addStyle(codebook, "Diary", rows = nrow(diaryCodebook) + 3, cols = 1:3, style = createStyle(wrapText = TRUE))
writeData(codebook, "Meta-info", startRow = nrow(metaInfo) + 3, startCol = 1, x = "Tabs of this file contain the respective codebooks for each data table.")
mergeCells(codebook, "Meta-info", cols = 1:3, rows = nrow(metaInfo) + 3)
setRowHeights(codebook, "Meta-info", rows = nrow(metaInfo) + 3, heights = 50)
saveWorkbook(codebook, "codebook.xlsx", overwrite = TRUE)3.6 Save data
Save the data to data-synthetic, for use in devising analysis scripts for e.g. the registered reports to come.
# Export as compressed CSV
# write_csv(synIntake, "data-synthetic/synIntake.csv.gz")
# write_csv(synDiary, "data-synthetic/synDiary.csv.gz")
# write_csv(synPanel, "data-synthetic/synPanel.csv.gz")
# write_csv(synXbox, "data-synthetic/synXbox.csv.gz")
# write_csv(synNintendo, "data-synthetic/synNintendo.csv.gz")
# write_csv(synAndroid, "data-synthetic/synAndroid.csv.gz")
# write_csv(synSteam, "data-synthetic/synSteam.csv.gz")
# write_csv(syniOS, "data-synthetic/syniOS.csv.gz")