R/IGT-functions.R

Defines functions IGT_calculator IGT_metrics IGT_count_RT_metrics IGT_load

Documented in IGT_calculator IGT_count_RT_metrics IGT_load IGT_metrics

library(tidyverse)
library(rprime)

# Decks 1 and 2 are bad
# Decks 3 and 4 are good

wm_path <- "/home/christian/Research/Brain_stuff/Iowa_Gambling_task/Iowa gambling-10182-2.txt"

#' IGT loader
#' 
#' Function to load IGT_data and convert necessary columns
#' @param wm_path specifies the file path to the eprime file of interest
#' @export
#' @return dataframe containing all eprime entries for Win, Loss, Score, loan, reaction times, sample, and response 
#' @keywords eprime, IGT


# Function to load IGT_data and convert necessary columns
IGT_load <- function(wm_path) {
  # Read in a text file generated by Eprime
  wm_lines <- rprime::read_eprime(wm_path)
  # Convert lines from an Eprime file into EprimeFrame objects
  wm_frames <- rprime::FrameList(wm_lines)
  # Make it a data frame.
  df <- rprime::to_data_frame(wm_frames) %>%
    
    # Convert data types 
    dplyr::mutate(Eprime.FrameNumber = as.numeric(Eprime.FrameNumber), 
           Won = as.numeric(Won),
           Lost = as.numeric(Lost),
           Score = as.numeric(Score),
           loan = as.numeric(loan),
           decks.RT = as.numeric(decks.RT),
           Sample = as.numeric(Sample),
           decks.RESP = as.numeric(decks.RESP)
           
    )
  df
}

#' IGT counter
#' 
#' Function to calculate count based metrics for the IGT task.
#' @param df dataframe containing the IGT task data
#' @export
#' @return dataframe containing LTC, IFL, Good, and Score summaries 
#' @keywords eprime, IGT

# a function to get count based metrics
IGT_count_RT_metrics <- function(df) {
  counts_RT <- df %>%
    dplyr::group_by(decks.RESP ) %>%
    dplyr::summarize(n = n(), RT = mean(decks.RT))
  
  
  
  ######################################
  # Learning of long-term consequences #
  ######################################
  # Bad decks
  bad <- sum(counts$n[counts$decks.RESP %in% c(1,2)])
  
  # Good decks
  good <-  sum(counts$n[counts$decks.RESP %in% c(3,4)])
  
  LTC <- good - bad
  
  # Final score
  Score <- df$Score[100]
  
  #############################
  # Bias for infrequenct loss #
  #############################
  
  # frequenct loss
  freq <- sum(counts$n[counts$decks.RESP %in% c(3,2)])
  
  # infrequenct loss
  infreq <-  sum(counts$n[counts$decks.RESP %in% c(1,4)])
  
  IFL <- infreq - freq
  
  # Return count results
  count_results <- tidyr::tibble("LTC" = LTC, "IFL" = IFL, "Good" = good, "Score" = Score)
  count_results
}



#' IGT metrics
#' 
#' Function to load IGT_data and and calculate summary values from the IGT task
#' @param wm_path specifies the file path to the eprime file of interest
#' @export
#' @return dataframe containing LTC, IFL, Good, reaction times, and score by subject and session 
#' @keywords eprime, IGT
#' @example 
#' # need to have rstudioapi, tidyverse, rprime, and wrapr
#' # install with 
#' # install.packages(c("rstudioapi", "tidyverse", "rprime", "wrapr"))
#' library(rstudioapi)
#'
#' # Enter the file path for the IGT .txt data
#' IGT_folder <- selectDirectory()
#'
#'
#' # End User input
#' ######################
#' # Source the script with ANT functions
#' source("Scripts/IGT-functions.R")
#'
#' # get all text files in folder
#' files <- list.files(IGT_folder)
#' files <- files[endsWith(files, ".txt")]
#'
#' results <-   results <- tibble()
#'
#'
#' for (file in files) {
#'   result <- IGT_metrics(paste0(IGT_folder, file))
#'
#'   results <- rbind(results, result)
#' }
#'
#' results


# A function to convert eprime text files to r dataframes
IGT_metrics <- function(wm_path) {
  
  df <- IGT_load(wm_path)
  # get subject and session info
  subject <- df[1,13]
  session <- df[1,14]
  
  # filter out Na's that occur every other observation
  df <- df %>% dplyr::filter(!is.na(decks.RT))

  
  # get count results
  count_res <- IGT_count_metrics(df)
  
  # get reaction time results 
  times <- df %>%
    dplyr::group_by(decks.RESP) %>%
    dplyr::summarize(ave= mean(decks.RT))
  
  deckA.RT <- times$ave[1]
  deckB.RT <- times$ave[2]
  deckC.RT <- times$ave[3]
  deckD.RT <- times$ave[4]
  
  
  # Cumulative counts to see trends in subject choices
  # cleaner <- experiment_df %>% dplyr::select(decks.RESP) %>% drop_na()
  # cool <- data.frame(cleaner$decks.RESP,count=ave(cleaner$decks.RESP==cleaner$decks.RESP, cleaner$decks.RESP, FUN=cumsum))
  
  # Visualize the trends for each subject
  # cool %>%
  #   mutate(ind = as.numeric(row.names(cool))) %>%
  #   ggplot(aes(x = ind, y = count, col= cleaner.decks.RESP)) + 
  #   geom_point()
  
  # return all IGt results
  results = tidyr::tibble("Subject" = subject, "Session" = session, "LTC" = count_res$LTC,
                   "IFL" = count_res$IFL, "Good" = count_res$Good,
                   "deckA.RT" = deckA.RT, "deckB.RT" = deckB.RT, "deckC.RT"= deckC.RT,
                   "deckD.RT"= deckD.RT, "Score"=  count_res$Score)
  
  results
  
}






#' Complete Attention systems calculator 
#'
#' A function that computes all of the IGT metrics for an entire folder of eprime data. Reteurns both  summarries for 
#' thirds of the experiment and for the whole observation (when thirds =0)
#' @param folder specifies the folder with the IGT data which you want to compute over. If unspecified it enters
#'               an interactive interface to select the directory
#' @param out specifies where to save results, default is to not save output 
#' @return Returns IGT metrics as well as Accuracy, reaction time, and corresponding third of experimetn metrics was computed off of for all subjects in the speciffied folder 
#'         Thirds refer to which third of the experimetnt the summariaes were calculated from. 0 refers to using the whole observation
#' @export



IGT_calculator <- function(folder = "NULL", out="NULL") {
  # if user doesn't define folder, have them select it
  if (folder == "NULL") {
    IGT_folder <- rstudioapi::selectDirectory()
  } else {
    IGT_folder <- folder
  }
  # Extract the files in that folder 
  files <- list.files(IGT_folder, full.names = TRUE)
  # select only the .txt files
  files <- files[grepl("*.txt$", files)]
  # Seed empty results dataframe to input results
  results <- data.frame()
  
  
  # compute attention network metrics for each experiment
  for (i in 1:(length(files))) {
    print(paste("Processing experiment", i))
    results <- rbind(results, IGT_metrics(files[[i]], thirds = FALSE))
    results <- rbind(results, IGT_metrics(files[[i]], thirds = TRUE))
  }
  
  #r1 <- results
  #r2 <- results
  #r3 <- results
  #### This is for storing and combining results from multiple years.
  
  #results <- rbind(r1, r2, r3)
  
  # save results as a csv if you want.
  if (out != "NULL") {
    write.csv(results, out) 
  }
  # return results
  results
}
coffm049/RAD.Lab documentation built on April 4, 2022, 10:35 a.m.