# Scale ID: 			PSS
# Scale Name: 		Perceived Stress Scale
# TILDA Variables: 	PSSscore
# Dataset:      		TILDA Waves 1-6
# Author:
# Institution:  		The Irish Longitudinal Study on Ageing (TILDA)
# 
# Description:
# Cleans and codes up summed score from the Perceived Stress Scale.
# 
# Version:      1.0
# Date:         2026-09-01
# Language:     R
#
# Assumption: the working data frame is called `data`.

recode_pss <- function(x, mapping) {
  out <- rep(NA_real_, length(x))
  # Stata recodes -845 through -99 inclusive to missing.
  out[!is.na(x) & x >= -845 & x <= -99] <- NA_real_
  for (i in seq_along(mapping)) {
    out[!is.na(x) & x == i] <- mapping[i]
  }
  out
}

data$PSS1 <- recode_pss(data$SCQPSS1, c(0,1,2,3,4))
data$PSS2 <- recode_pss(data$SCQPSS2, c(4,3,2,1,0))
data$PSS3 <- recode_pss(data$SCQPSS3, c(4,3,2,1,0))
data$PSS4 <- recode_pss(data$SCQPSS4, c(0,1,2,3,4))

# Ordinary addition: any missing component gives a missing total.
data$PSSscore <- data$PSS1 + data$PSS2 + data$PSS3 + data$PSS4

data[c("PSS1","PSS2","PSS3","PSS4")] <- NULL

attr(data$PSSscore, "label") <- "Perceived Stress Scale (0-16)"
attr(data$PSSscore, "note") <- paste(
  "4-item Perceived Stress Scale from Self-completion questionnaire,",
  "scores range from 0 to 16, higher score indicates greater stress"
)
