Last active
May 5, 2016 07:20
-
-
Save christophergandrud/63d295e68c51833292e44bce7f951292 to your computer and use it in GitHub Desktop.
Find key features of a spell including and ordered spell ID and each spell's duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Find key features of a spell including and ordered spell ID and each spell's | |
#' duration | |
#' | |
#' @param x a time ordered vector with values identifying a spell. It is | |
#' assumed that when a value in this vector changes that the spell has ended. | |
#' @param id logical specifying whether or not to return the spell ID | |
#' @param duration logical specifying whether or not to return the spell | |
#' duration. | |
#' | |
#' @examples | |
#' # Create fake data | |
#' x <- c('a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'a', 'a') | |
#' Find spell features | |
#' spell_features(x) | |
#' | |
#' @importFrom dplyr %>% group_by mutate | |
#' | |
#' @export | |
spell_features <- function(x, id = TRUE, duration = TRUE) { | |
require(dplyr) | |
message('Assumption: x is in the correct time order.\n') | |
temp <- data.frame(x = x, x1 = c(NA, x[-length(x)])) | |
# Find spell ID | |
temp$spell_id[is.na(temp$x1)] <- 1 | |
for (i in 2:nrow(temp)) { | |
if (temp[i, 1] == temp[i, 2]) temp[i, 3] <- temp[(i - 1), 3] | |
else temp[i, 3] <- temp[(i - 1), 3] + 1 | |
} | |
# Find spell duration | |
if (isTRUE(duration)) { | |
temp$fake <- 1 | |
temp <- temp %>% group_by(spell_id) %>% mutate(duration = cumsum(fake)) | |
temp <- as.data.frame(temp) | |
} | |
if (isTRUE(id) & isTRUE(duration)) { | |
out <- temp[, c('spell_id', 'duration')] | |
} | |
else if (!isTRUE(duration)) { | |
out <- temp[, 'spell_id'] | |
} | |
else if (!isTRUE(id)) { | |
out <- temp[, 'duration'] | |
} | |
return(out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment