Skip to content

Instantly share code, notes, and snippets.

@jvcasillas
Last active August 29, 2015 14:11
Show Gist options
  • Save jvcasillas/78300788c66e8cf570bf to your computer and use it in GitHub Desktop.
Save jvcasillas/78300788c66e8cf570bf to your computer and use it in GitHub Desktop.
dPrime
#####################################
# Functions for linguistic research #
# Joseph V. Casillas #
# Last update: 12-10-2014 #
#####################################
# Calculate d prime in discrimination experiments.
# Takes a df with the columns:
# - stimDiff (actual stimuli are different)
# - stimSame (actual stimuli are the same)
# Each column has responses of 'diff' or 'same'
dPrime <- function(df, stimDiff, stimSame) {
# Calculate number of same, diff and total responses
# for the stimuli that were actually different
stimDiffRdiff <- nrow(df[df$stimDiff == 'diff', ])
stimDiffRsame <- nrow(df[df$stimDiff == 'same', ])
stimDiffTotal <- length(df$stimDiff)
# Calculate number of same, diff and total responses
# for the stimuli that were actually the same
stimSameRdiff <- nrow(df[df$stimSame == 'diff', ])
stimSameRsame <- nrow(df[df$stimSame == 'same', ])
stimSameTotal <- length(df$stimSame)
# Hit rate = the number of correct responses 'diff'
# when the stimuli were actually diff, divided by
# the total number of responses
hitRate <- stimDiffRdiff / stimDiffTotal
# Miss rate = the number of incorrect responses
# 'same' when the stimuli were actually diff
# divided by the total number of responses
missRate <- stimDiffRsame / stimDiffTotal
# False alarm = the number responses 'diff'
# when the stimuli were actually the same
# divided by the total number of responses
falseAlarm <- stimSameRdiff / stimSameTotal
# Correct rejection = the number of responses
# same when the stimuli were actually the same
# divided by the number of total responses
corrReject <- stimSameRsame / stimSameTotal
# Calculate z-critical values for hit rate
# and false alarm rate
zHitRate <- qnorm(hitRate)
zFalseAlarm <- qnorm(falseAlarm)
# Calculate d prime
ret = dPrime <- zHitRate - zFalseAlarm
return(ret)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment