knitr::opts_chunk$set(echo = TRUE)

Import pbc msw

library(readr)
var_details <- read_csv("../inst/extdata/PBC-variableDetails.csv")
variables <- read_csv("../inst/extdata/PBC-variables.csv")

Import the pbc data

library(survival)
data("pbc")

Recode data with the msw

library(bllflow)
recoded_pbc <- rec_with_table(data_source = pbc, variable_details = var_details, dataset_name = "survival-pbc")

Compare the recode

print(pbc)
print(recoded_pbc[,c("TIME","STATUS","TRT","AGE","SEX","ASCITES","HEPATO","SPIDERS","EDEMA","BILI","CHOL","ALBUMIN","COPPER","ALK_PHOS","AST","TRIG","PLATELET","PROTIME","STAGE")])

Write custom function for calculating age group

custom_age_group_calculation <- function(age){
  # Feel free to write ur own code this is an example
  return(trunc(age/10))
}

Create a new variable that uses age group

I will use R code to create one row for the new variable, then rowbind it with existing variable details feel free to change any elements u wish just make sure its consistent with the function arguments.

new_row <- data.frame(variable = "Age_Group_Using_Custom_Variable", to_type = "cont", database_start = "survival-pbc", variable_start = "DerivedVar::[AGE_GROUP, SPIDERS]", from_type = "cont", rec_to = "Func::CustomRandomFunction", cat_label = "NA", cat_label_long ="NA", units = "NA", rec_from = "else", cat_start_label = NA, notes = NA, interval = NA)
var_details <- rbind(var_details,new_row)

Create the other custom function

custom_random_function <- function(age_group, spiders) {
  # make sure to account for na since in R anything == NA equaites to NA and causes errors
  if (is.na(spiders)) {
  age_group <- age_group
  }
  else if (spiders == "1") {
  age_group = age_group + 5
  } else if (spiders == "2") {
  age_group = age_group - 5
  }

  return(ageGroup)
}

Rerun the recode function to create new variable

recoded_PBC <- rec_with_table(data_source = pbc, variable_details = var_details, dataset_name = "survival-pbc")
print(recoded_PBC)


Big-Life-Lab/bllflow documentation built on Feb. 1, 2023, 12:29 p.m.