R/readStatsFile.R

#' Collect data from a standard world/stats directory
#' 
#' code{readStatsFile} is meant to parse the stats files located in a 
#' world/stats dir (since Minecraft 1.7). It reads a \code{<UUID>.json} file and
#' returns it as a \code{data.frame}
#' @name readStatsFile
#' @family playerstats, API import
#' @import tools
#' @param file The stats file (JSON) to parse, usually located in the server 
#'   world directory, e.g. \code{world/stats}
#' @param dropPrefixes Strips the \code{stat.} or \code{achievement.} prefixes
#' from the variable names. Defaults to \code{TRUE}.
#' @return A \code{data.frame} containing every stat contained in the file as a 
#'   column name
#' @export
#' @seealso \code{\link{getNameFromUUID}}
#' @note If you want to combine multiple \code{data.frames} imported with this function,
#' you could do so using \code{\link[plyr]{rbind.fill}}, since it is very unlikely
#' that each \code{data.frame} will have the same columns present, hence 
#' \code{\link[base]{rbind}} is likely to fail.
#' @examples
#' \dontrun{
#' require(plyr) # For rbind.fill
#' playerstats <- data.frame()
#' for(file in dir("server/world/stats")){
#'  stat <- readStatsFile(paste0("server/world/stats", file))
#'  playerstats <<- rbind.fill(stat, playerstats)
#' }
#' }
readStatsFile <- function(file, dropPrefixes = TRUE){
  path       <- str_split(file_path_sans_ext(file), "/")
  UUID       <- path[[1]][length(path[[1]])]
  stats.list <- jsonlite::fromJSON(file)
  stats.df   <- data.frame(UUID = UUID, stats.list[names(stats.list) != "achievement.exploreAllBiomes"],
                           stringsAsFactors = FALSE)
  stats.df$achievement.exploreAllBiomes.value    <- stats.list$achievement.exploreAllBiomes$value
  # Add number of explored biomes as an extra variable
  stats.df$achievement.exploreAllBiomes.num      <- length(stats.list$achievement.exploreAllBiomes$progress)
  # Add biome progress
  stats.df$achievement.exploreAllBiomes.progress <- I(list(stats.list$achievement.exploreAllBiomes$progress))
  
  if (dropPrefixes){
    names(stats.df) <- sub("stat.",        "", names(stats.df))
    names(stats.df) <- sub("achievement.", "", names(stats.df))
  }
  
  return(stats.df)
}
jemus42/wurstmineR documentation built on May 19, 2019, 4:03 a.m.