R/ICCLONG.R

Defines functions ICC_long

Documented in ICC_long

#' @title Intra-class Correlation Coefficient (ICC) for a set of athlete measurements, with the data in long format
#'
#' @description Computes the ICC for each vector of measurements that is passed to the function, for the subject and trial vectors
#'
#' @param subject The vector of athletes who recorded the results for each metric (can be a numeric or factor variable)
#' @param trial The vector that represents which trial each measurement came from
#' @param ... Numeric vectors that represent the metrics for which the ICC output should be given. These vectors hold the scores that
#'   each athlete recorded for each respective metric (at least one metric must be passed to the function).
#'
#' @return A list, with its contents being the ICC output (containing the six types of ICC's, as generated by psych::ICC()), is
#'   returned
#'
#' @examples
#' subject <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
#' trial <- c(1, 2, 3, 1, 2, 3, 1, 2, 3)
#' metric_1 <- c(250, 258, 252, 279, 270, 277, 218, 213, 218)
#' metric_2 <- c(10, 7, 10, 14, 18, 17, 11, 7, 8)
#' metric_3 <- c(1214, 1276, 1289, 1037, 1010, 1069, 1481, 1465, 1443)
#' ICC_long(subject, trial, metric_1, metric_2, metric_3)
#'
#' @references Shrout, P. E., &amp; Fleiss, J. L. (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological
#'   Bulletin, 86(2), 420-428.
#'
#' @export
ICC_long <- function(subject, trial, ...) {

  # The inputs to this function are individual vectors, so here they are brought together into one data frame
  input_df <- data.frame(subject, trial, ...)

  # Calls the check_error function, which produces informative error messages if any of a variety of errors are made by the user
  check_error(subject, trial, ...)

  # This for loop iterates over the arguments passed to the function that represent the measurements for the various metrics
  for (i in 3:nargs()) {

    # For each loop, we want to make a new dataset with only three columns: subject, trial, and the ith metric in the for loop
    df <- input_df[, c(1, 2, i)]

    # Converts the data frame to the wide format needed to use the ICC function from the psych package later on
    df <- tidyr::pivot_wider(df, names_from = trial, values_from = colnames(input_df)[i])

    # The vector of subjects must not be part of the data frame in order to use the ICC function from the psych package
    df <- df[, -1]

    # Computes the ICC for the metric and converts it into a list
    ICC = psych::ICC(df)
    list_ICC <- list(ICC)

    # Names each item in the list according to the name of its metric, and then prints it
    names(list_ICC) <- colnames(input_df)[i]
    print(list_ICC)

  }

}

Try the psr package in your browser

Any scripts or data that you put into this service are public.

psr documentation built on Aug. 13, 2021, 5:08 p.m.