R/mergeItemStats.R

#' Merge old and new item stat IDs
#' 
#' This function merges the old (numerical) and new item IDs in the
#' item stats dataframe. The item dataset must have gone through 
#' \link[wurstmineR]{stats2df} beforehand.
#' @keywords items
#' @param items The items dataset
#' @param itemData The dataset of descriptive item strings, see \link[wurstmineR]{strings.items}
#' @return \code{data.frame} of item stats, with only new item IDs
#' @export
#' @note Not related to \code{itemStats}, the dataset of per-item stats.
#' @examples
#' \dontrun{
#' items <- stats2df(fromJSON("http://api.wurstmineberg.de/server/playerstats/item.json"))
#' items <- mergeItemStats(items, strings.items)
#' }
mergeItemStats <- function(items = NULL, itemData = NULL){
  if (is.null(itemData)){
    itemData <- wurstmineR::strings.items
  }
  ## Get table of item actions and readable names ##
  itemActions <- data.frame(id    = c("mineBlock", "craftItem"   , "useItem" , "breakItem"), 
                            name  = c("mined"    , "crafted"     , "used"    , "broken"))
  # Get list of num and new IDs actually existing in items dataset
  existingNumIDs <- names(items)[grep("\\.[0-9]+$", names(items))]
  for(action in itemActions$id){
    existingNumIDs <- sub(paste0(action, "."), "", existingNumIDs)
  }; rm(action)
  
  # I honestly have no idea anymore what I did here, but it merges old and new item stats
  tempStats <- items[ , !names(items) %in% names(items)[grep("\\.[0-9]+$", names(items))]]
  tempStats <- as.character(names(tempStats)[grep("[^player]", names(tempStats))])
  
  for(i in 1:length(existingNumIDs)){
    for(action in itemActions$id){
      ID <- itemData$ID[itemData$numID == existingNumIDs[i]]
      
      if(paste(action, ".", ID, sep="") %in% tempStats){
        newIDstat <- items[, paste(action, ".", ID, sep="")]
        
        if(paste(action, ".", existingNumIDs[i], sep="") %in% names(items)){
          oldIDstat <- items[, paste(action, ".", existingNumIDs[i], sep="")]
          items[, paste(action, ".", ID, sep="")] <- newIDstat + oldIDstat
        }
      }
    }
  }
  # Exclude now unneeded old item ID columns
  items <- items[ , !names(items) %in% names(items)[grep("\\.[0-9]+$", names(items))]]
  return(items)
}
jemus42/wurstmineR documentation built on May 19, 2019, 4:03 a.m.