# codebook_generation_01.R
#
# Code generation example
#
# Input:  results/data_rdm-ms-ss2024_cleaned.RData
# Output: 
#
# created: 2024-06-04

# setwd("C:/Users/nwickelmaier/Nextcloud/Documents/teaching/iwm/data_management/03_data_organisation/example/")

dat <- as.data.frame(haven::read_spss("data/rawdata/RDM_MS_SS2024_download_2024-06-04.sav"))

## Fix data_sharing_2
dat$data_sharing_2[dat$data_sharing_2 == "1 out of 4"] <- 1

# Look at attributes
attributes(dat$sex)

# Create codebook with survey questions
codebook <- data.frame(variable = names(dat),
                       label = sapply(dat, function(x) attr(x, "label")))

# Clean up data frame
dat <- as.data.frame(lapply(dat, sjlabelled::unlabel))

sapply(dat, class)  # Look at classes

dat$age <- as.numeric(dat$age)
dat$career_level_2 <- as.numeric(dat$career_level_2)
dat$data_sharing_2 <- as.numeric(dat$data_sharing_2)

dat$sex <- factor(dat$sex,
                  levels = 1:4,
                  labels = names(attr(dat$sex, "labels")))
dat$data_sharing_1 <- factor(dat$data_sharing_1,
                             levels = 1:2,
                             labels = names(attr(dat$data_sharing_1, "labels")))
dat$career_level_1 <- factor(dat$career_level_1,
                             levels = 1:6,
                             labels = names(attr(dat$career_level_1, "labels")))

# Add descriptive statistics to codebook

codebook$n <- sapply(dat, length)
codebook$type <- sapply(dat, class)
codebook$mean <- sapply(dat, function(x) ifelse(is.numeric(x), mean(x, na.rm = TRUE), NA))
codebook$sd <- sapply(dat, function(x) ifelse(is.numeric(x), sd(x), NA))

# props <- function(x) {
#   if (is.factor(x)) {
#     proportions(summary(x))
#   } else {
#     NA
#   }
# }
# 
# codebook$prop <- lapply(dat, props)

write.table(codebook,
            file = "data/codebook/codebook_02.csv",
            na = "",
            sep = ";",
            quote = FALSE) 

openxlsx::write.xlsx(codebook, file = "data/codebook/codebook_02.xlsx")


