content
stringlengths
0
14.9M
filename
stringlengths
44
136
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. `tformat` <- function(x, ...) { UseMethod('tformat') } `tformat<-` <- function(x, value) { UseMethod('tformat<-') } `tformat.default` <- function(x, ...) { attr(x, 'tformat') } `tormat<-.default` <- function(x, value) { attr(x, '.tformat') <- value x } `tformat.xts` <- function(x, ...) { ix <- .index(x) attr(ix, 'tformat') } `tformat<-.xts` <- function(x, value) { if(!is.character(value) && !is.null(value)) stop('must provide valid POSIX formatting string') # Remove format attrs (object created before 0.10-3) attr(x, ".indexFORMAT") <- NULL attr(attr(x, 'index'), 'tformat') <- value x } `indexFormat` <- function(x) { .Deprecated("tformat", "xts") tformat(x) } `indexFormat<-` <- function(x, value) { .Deprecated("tformat<-", "xts") `tformat<-`(x, value) }
/scratch/gouwar.j/cran-all/cranData/xts/R/tformat.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. `timeBasedRange` <- function(x, ...) { # convert unquoted time range to if (!is.character(x)) x <- deparse(match.call()$x) # determine start and end points tblist <- timeBasedSeq(x,NULL) # if(!is.null(tblist$length.out)) # return(tblist$from) c(as.numeric(tblist$from), as.numeric(tblist$to)) }
/scratch/gouwar.j/cran-all/cranData/xts/R/timeBasedRange.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. `timeBasedSeq` <- function(x, retclass=NULL, length.out=NULL) { if(!is.character(x)) # allows for unquoted numerical expressions to work x <- deparse(match.call()$x) x <- gsub('::','/',x, perl=TRUE) # replace all '::' range ops with '/' x <- gsub('[-:]','',x, perl=TRUE) # strip all remaining '-' and ':' seps x <- gsub('[ ]','',x, perl=TRUE) # strip all remaining white space x <- unlist(strsplit(x,"/")) from <- x[1] to <- x[2] BY <- x[3] # need to test for user specified length.out, currently just overriding if(from == "") from <- NA if(!is.na(from)) { year <- as.numeric(substr(from,1,4)) month <- as.numeric(substr(from,5,6)) day <- as.numeric(substr(from,7,8)) hour <- as.numeric(substr(from,9,10)) mins <- as.numeric(substr(from,11,12)) secs <- as.numeric(substr(from,13,14)) time.args.from <- as.list(unlist(sapply(c(year,month,day,hour,mins,secs), function(x) if(!is.na(x)) x) )) from <- do.call('firstof',time.args.from) } else time.args.from <- list() # only calculate if to is specified if(!is.na(to)) { year <- as.numeric(substr(to,1,4)) month <- as.numeric(substr(to,5,6)) day <- as.numeric(substr(to,7,8)) hour <- as.numeric(substr(to,9,10)) mins <- as.numeric(substr(to,11,12)) secs <- as.numeric(substr(to,13,14)) time.args.to <- as.list(unlist(sapply(c(year,month,day,hour,mins,secs), function(x) if(!is.na(x)) x) )) to <- do.call('lastof',time.args.to) } else time.args.to <- list() max.resolution <- max(length(time.args.from), length(time.args.to)) # if neither is set if(max.resolution == 0) max.resolution <- 1 resolution <- c('year','month','DSTday','hour','mins','secs')[max.resolution] if(!is.na(BY)) resolution <- names(match.arg(BY, list(year ='Y', month ='m', day ='d', hour ='H', mins ='M', secs ='S'))) convert.to <- 'Date' if(max.resolution == 2 || resolution == 'month' ) convert.to <- 'yearmon' if(max.resolution > 3 || resolution %in% c("hour","mins","secs")) convert.to <- 'POSIXct' if(is.na(to) && missing(length.out)) length.out <- 1L if(((!missing(retclass) && is.null(retclass)) || any(is.na(to),is.na(from)))) { # return the calculated values only return(list(from=from,to=to,by=resolution,length.out=length.out)) } if(is.null(length.out)) { SEQ <- seq(from,to,by=resolution) } else { SEQ <- seq(from, by=resolution, length.out=length.out) } if(!is.null(retclass)) convert.to <- retclass if(convert.to == 'POSIXct') { structure(SEQ, class=c('POSIXct','POSIXt')) # need to force the TZ to be used } else do.call(paste('as',convert.to,sep='.'), list(SEQ)) }
/scratch/gouwar.j/cran-all/cranData/xts/R/timeBasedSeq.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. as.xts.timeDate <- function(x, ...) { xts(x=NULL, order.by=x) }
/scratch/gouwar.j/cran-all/cranData/xts/R/timeDate.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # functions to handle timeSeries <--> xts conversions `re.timeSeries` <- function(x,...) { if(!requireNamespace('timeSeries', quietly=TRUE)) { timeSeries <- function(...) message("package 'timeSeries' is required") } else { timeSeries <- timeSeries::timeSeries } # strip all non-'core' attributes so they're not attached to the Data slot x.attr <- attributes(x) xx <- structure(x,dimnames=x.attr$dimnames,index=x.attr$index) original.attr <- attributes(x)[!names(attributes(x)) %in% c("dim","dimnames","index","class")] for(i in names(original.attr)) { attr(xx,i) <- NULL } timeSeries(coredata(xx),charvec=as.POSIXct(format(index(x)),tz="GMT"),format=x.attr$format, zone=x.attr$FinCenter,FinCenter=x.attr$FinCenter, recordIDs=x.attr$recordIDs,title=x.attr$title, documentation=x.attr$documentation,...) } `as.xts.timeSeries` <- function(x,dateFormat="POSIXct",FinCenter,recordIDs,title,documentation,..., .RECLASS=FALSE) { if(missing(FinCenter)) FinCenter <- x@FinCenter if(missing(recordIDs)) recordIDs <- x@recordIDs if(missing(title)) title <- x@title if(missing(documentation)) documentation <- x@documentation indexBy <- structure(x@positions, class=c("POSIXct","POSIXt"), tzone=FinCenter) order.by <- do.call(paste('as',dateFormat,sep='.'),list(as.character(indexBy))) if(.RECLASS) { xts(as.matrix([email protected]), order.by=order.by, format=x@format, FinCenter=FinCenter, recordIDs=recordIDs, title=title, documentation=documentation, .CLASS='timeSeries', .CLASSnames=c('FinCenter','recordIDs','title','documentation','format'), .RECLASS=TRUE, ...) } else { xts(as.matrix([email protected]), order.by=order.by, ...) } } as.timeSeries.xts <- function(x, ...) { if(!requireNamespace('timeSeries', quietly=TRUE)) { timeSeries <- function(...) message("package 'timeSeries' is required") } else { timeSeries <- timeSeries::timeSeries } timeSeries(data=coredata(x), charvec=as.character(index(x)), ...) } `xts.as.timeSeries` <- function(x,...) {}
/scratch/gouwar.j/cran-all/cranData/xts/R/timeSeries.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # to.period functionality from quantmod # # to.period base function # to.minutes # to.hourly # to.daily # to.weekly # to.monthly # to.quarterly # to.yearly to.period <- to_period <- function(x, period='months', k=1, indexAt=NULL, name=NULL, OHLC=TRUE, ...) { if(missing(name)) name <- deparse(substitute(x)) xo <- x x <- try.xts(x) if(NROW(x)==0 || NCOL(x)==0) stop(sQuote("x")," contains no data") if(any(is.na(x))) { x <- na.omit(x) warning("missing values removed from data") } if(is.character(period)) { ep <- endpoints(x, period, k) } else { if(!is.numeric(period)) { stop("'period' must be a character or a vector of endpoint locations") } if(!missing("k")) { warning("'k' is ignored when using custom 'period' locations") } if(!is.null(indexAt)) { warning("'indexAt' is ignored when using custom 'period' locations") indexAt <- NULL } ep <- as.integer(period) # ensure 'ep' starts with 0 and ends with nrow(x) if(ep[1] != 0) { ep <- c(0L, ep) } if (ep[length(ep)] != NROW(x)) { ep <- c(ep, NROW(x)) } } if(!OHLC) { xx <- x[ep, ] } else { if(!is.null(indexAt)) { index_at <- switch(indexAt, "startof" = TRUE, # start time of period "endof" = FALSE, # end time of period FALSE ) } else index_at <- FALSE # make suitable name vector cnames <- c("Open", "High", "Low", "Close") if (has.Vo(x)) cnames <- c(cnames, "Volume") if (has.Ad(x) && is.OHLC(x)) cnames <- c(cnames, "Adjusted") cnames <- paste(name,cnames,sep=".") if(is.null(name)) cnames <- NULL xx <- .Call(C_toPeriod, x, ep, has.Vo(x), has.Vo(x,which=TRUE), has.Ad(x) && is.OHLC(x), index_at, cnames) } if(!is.null(indexAt)) { if(indexAt=="yearmon" || indexAt=="yearqtr") tclass(xx) <- indexAt if(indexAt=="firstof") { ix <- as.POSIXlt(c(.index(xx)), tz=tzone(xx)) if(period %in% c("years","months","quarters","days")) index(xx) <- firstof(ix$year + 1900, ix$mon + 1) else index(xx) <- firstof(ix$year + 1900, ix$mon + 1, ix$mday, ix$hour, ix$min, ix$sec) } if(indexAt=="lastof") { ix <- as.POSIXlt(c(.index(xx)), tz=tzone(xx)) if(period %in% c("years","months","quarters","days")) index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon + 1)) else index(xx) <- lastof(ix$year + 1900, ix$mon + 1, ix$mday, ix$hour, ix$min, ix$sec) } } reclass(xx,xo) } `to.minutes` <- function(x,k,name,...) { if(missing(name)) name <- deparse(substitute(x)) if(missing(k)) k <- 1 to.period(x,'minutes',k=k,name=name,...) } `to.minutes3` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'minutes',k=3,name=name,...) } `to.minutes5` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'minutes',k=5,name=name,...) } `to.minutes10` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'minutes',k=10,name=name,...) } `to.minutes15` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'minutes',k=15,name=name,...) } `to.minutes30` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'minutes',k=30,name=name,...) } `to.hourly` <- function(x,name,...) { if(missing(name)) name <- deparse(substitute(x)) to.period(x,'hours',name=name,...) } `to.daily` <- function(x,drop.time=TRUE,name,...) { if(missing(name)) name <- deparse(substitute(x)) x <- to.period(x,'days',name=name,...) if(drop.time) x <- .drop.time(x) return(x) } `to.weekly` <- function(x,drop.time=TRUE,name,...) { if(missing(name)) name <- deparse(substitute(x)) x <- to.period(x,'weeks',name=name,...) if(drop.time) x <- .drop.time(x) return(x) } `to.monthly` <- function(x,indexAt='yearmon',drop.time=TRUE,name,...) { if(missing(name)) name <- deparse(substitute(x)) x <- to.period(x,'months',indexAt=indexAt,name=name,...) if(drop.time) x <- .drop.time(x) return(x) } `to.quarterly` <- function(x,indexAt='yearqtr',drop.time=TRUE,name,...) { if(missing(name)) name <- deparse(substitute(x)) x <- to.period(x,'quarters',indexAt=indexAt,name=name,...) if(drop.time) x <- .drop.time(x) return(x) } `to.yearly` <- function(x,drop.time=TRUE,name,...) { if(missing(name)) name <- deparse(substitute(x)) x <- to.period(x,'years',name=name,...) if(drop.time) x <- .drop.time(x) return(x) } `.drop.time` <- function(x) { # function to remove HHMMSS portion of time index xts.in <- is.xts(x) # is the input xts? if(!xts.in) # if not, try to convert to xts x <- try.xts(x, error=FALSE) if(is.xts(x)) { # if x is xts, drop HHMMSS from index if(any(tclass(x)=='POSIXt')) { # convert index to Date index(x) <- as.Date(as.POSIXlt(index(x))) tclass(x) <- "Date" # set tclass to Date } if(isClassWithoutTZ(tclass(x))) { tzone(x) <- "UTC" # set tzone to UTC } # force conversion, even if we didn't set tclass to Date # because indexAt yearmon/yearqtr won't drop time from index index(x) <- index(x) if(xts.in) x # if input already was xts else reclass(x) # if input wasn't xts, but could be converted } else x # if input wasn't xts, and couldn't be converted } `by.period` <- function(x, FUN, on=Cl, period="days", k=1, fill=na.locf, ...) { # aggregate 'x' to a higher periodicity, apply 'FUN' to the 'on' columns # of the aggregate, then merge the aggregate results with 'x' and fill NAs # with na.locf. E.g. you can apply a 5-day SMA of volume to tick data. x <- try.xts(x, error = FALSE) FUN <- match.fun(FUN) on <- match.fun(on) # Allow function or name agg <- to.period(x, period, k, ...) res <- FUN(on(agg), ...) full <- merge(.xts(NULL,index(x)),res) full <- fill(full) # Allow function or value return(full) } `to.frequency` <- function(x, by, k=1, name=NULL, OHLC=TRUE, ...) { # similar to to.period, but aggregates on something other than time. # E.g. aggregate by volume, where a "period" is 10% of the 5-day volume SMA. # Most code pulled from to.period if(missing(name)) name <- deparse(substitute(x)) xo <- x x <- try.xts(x) if(any(is.na(x))) { x <- na.omit(x) warning("missing values removed from data") } # if(!OHLC) { # xx <- x[endpoints(x, period, k),] # } else { # if(!is.null(indexAt)) { # index_at <- switch(indexAt, # "startof" = TRUE, # start time of period # "endof" = FALSE, # end time of period # FALSE # ) # } else index_at <- FALSE # make suitable name vector cnames <- c("Open", "High", "Low", "Close") if (has.Vo(x)) cnames <- c(cnames, "Volume") if (has.Ad(x) && is.OHLC(x)) cnames <- c(cnames, "Adjusted") cnames <- paste(name,cnames,sep=".") if(is.null(name)) cnames <- NULL # start to.frequency-specific code if (missing(by)) by <- rep(1L, nrow(x)) byVec <- cumsum(by) bins <- byVec %/% k # ep contents must have the same format as output generated by endpoints(): # first element must be zero and last must be nrow(x) ep <- c(0L, which(diff(bins) != 0)) if (ep[length(ep)] != nrow(bins)) ep <- c(ep, nrow(bins)) # end to.frequency-specific code xx <- .Call(C_toPeriod, x, ep, has.Vo(x), has.Vo(x,which=TRUE), has.Ad(x) && is.OHLC(x), FALSE, cnames) reclass(xx,xo) }
/scratch/gouwar.j/cran-all/cranData/xts/R/toperiod.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # methods for handling ts <--> xts #`re.ts2` <- #function(x,...) { # # attempt to provide a more robust reclass 'ts' method # na.replace <- function(x) { # na.removed <- attr(x,'na.action') # if(class(na.removed) != 'omit') return() # nrows <- NROW(x) # xx <- vector('numeric',length=(nrows+length(na.removed))) # xx[ na.removed,] <- NA # xx[-na.removed] <- x # xx # } #} `re.ts` <- function(x,...) { # major issue with quick reclass. Basically fails on data < 1970... #tsp.attr <- attr(x,'.tsp') #freq.attr <- attr(x,'.frequency') #xtsAttributes(x) <- NULL #ts(coredata(x), start=tsp.attr[1],frequency=freq.attr) dim <- attr(x, 'dim') if(!is.null(dim) && dim[2]==1) { attr(x,'dim') <- attr(x, 'dimnames') <- NULL } as.ts(x) } `as.xts.ts` <- function(x,dateFormat,...,.RECLASS=FALSE) { x.mat <- structure(as.matrix(x),dimnames=dimnames(x)) colnames(x.mat) <- colnames(x) # quick hueristic - if numeric index is larger than one # full day of seconds (60*60*24) than use POSIXct, otherwise # assume we are counting my days, not seconds, and use Date -jar # # I am sure this can be improved upon, but for now it is effective # in most circumstances. Will break if frequency or time is from 1 # not _break_ but be less useful # a bigger question is _should_ it throw an error if it can't guess, # or should the user simply beware. if(missing(dateFormat)) { if(frequency(x) == 1) { # assume yearly series: Date yr <- tsp(x)[1] %/% 1 mo <- tsp(x)[1] %% 1 if(mo %% (1/12) != 0 || yr > 3000) { # something finer than year.month is specified - can't reliable convert dateFormat <- ifelse(max(time(x)) > 86400,'POSIXct','Date') order.by <- do.call(paste('as',dateFormat,sep='.'), list(as.numeric(time(x)),origin='1970-01-01',...)) } else { mo <- ifelse(length(mo) < 1, 1,floor(mo * 12)+1) from <- as.Date(firstof(yr,mo),origin='1970-01-01') order.by <- seq.Date(from,length.out=length(time(x)),by='year') } } else if(frequency(x) == 4) { # quarterly series: yearqtr order.by <- as.yearqtr(time(x)) } else if(frequency(x) == 12) { # monthly series: yearmon order.by <- as.yearmon(time(x)) } else stop('could not convert index to appropriate type') } else { order.by <- do.call(paste('as',dateFormat,sep='.'), list(as.numeric(time(x)),...)) } if(.RECLASS) { xx <- xts(x.mat, order.by=order.by, frequency=frequency(x), .CLASS='ts', .CLASSnames=c('frequency'), .tsp=tsp(x), # .frequency=frequency(x), ...) } else { xx <- xts(x.mat, order.by=order.by, frequency=frequency(x), ...) } attr(xx, 'tsp') <- NULL xx } `as.ts.xts` <- function(x,...) { #if(attr(x,'.CLASS')=='ts') return(re.ts(x,...)) TSP <- attr(x, '.tsp') attr(x, '.tsp') <- NULL x <- ts(coredata(x), frequency=frequency(x), ...) if(!is.null(dim(x)) && dim(x)[2]==1) dim(x) <- NULL if(!is.null(TSP)) tsp(x) <- TSP x }
/scratch/gouwar.j/cran-all/cranData/xts/R/ts.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. indexTZ <- function(x, ...) { .Deprecated("tzone", "xts") tzone(x, ...) } tzone <- function(x, ...) { UseMethod("tzone") } `indexTZ<-` <- function(x, value) { .Deprecated("tzone<-", "xts") `tzone<-`(x, value) } `tzone<-` <- function(x, value) { UseMethod("tzone<-") } `tzone<-.xts` <- function(x, value) { if (is.null(value)) { value <- "" } tzone <- as.character(value) attr(attr(x, "index"), "tzone") <- tzone # Remove tz attrs (object created before 0.10-3) attr(x, ".indexTZ") <- NULL attr(x, "tzone") <- NULL x } tzone.default <- function(x, ...) { attr(x, "tzone") } `tzone<-.default` <- function(x, value) { if (!is.null(value)) { value <- as.character(value) } attr(x, "tzone") <- value x } tzone.xts <- function(x, ...) { tzone <- attr(attr(x, "index"), "tzone") # For xts objects created pre-0.10.3 if (is.null(tzone)) { # no tzone on the index sq_tzone <- sQuote("tozne") sq_both <- paste(sq_tzone, "or", sQuote(".indexTZ")) warn_msg <- paste0("index does not have a ", sq_tzone, " attribute") tzone <- attr(x, "tzone") if (is.null(tzone)) { # no tzone on the xts object, look for .indexTZ tzone <- attr(x, ".indexTZ") } if (is.null(tzone)) { # no .indexTZ on the xts object tzone <- "" warn_msg <- paste0(warn_msg, "\n and xts object does not have a ", sq_both, " attribute\n", " returning ", dQuote(tzone)) warning(warn_msg) return(tzone) } sym <- deparse(substitute(x)) warning(warn_msg, "\n use ", sym, " <- xts:::.update_index_attributes(", sym, ") to update the object") } return(tzone) } isClassWithoutTZ <- function(tclass, object = NULL) { .classesWithoutTZ <- c("chron","dates","times","Date","yearmon","yearqtr") has_no_tz <- FALSE if (is.null(object)) { has_no_tz <- any(tclass %in% .classesWithoutTZ) } else { has_no_tz <- inherits(object, .classesWithoutTZ) } return(has_no_tz) } isUTC <- function(tz = NULL) { if (is.null(tz)) { tz <- Sys.timezone() } switch(tz, "UTC" = , "GMT" = , "Etc/UTC" = , "Etc/GMT" = , "GMT-0" = , "GMT+0" = , "GMT0" = TRUE, FALSE) } check.TZ <- function(x, ...) { check <- getOption("xts_check_TZ") if (!is.null(check) && !check) { return() } x_tz <- tzone(x) x_tclass <- tclass(x) if (isClassWithoutTZ(x_tclass)) { # warn if tzone is not UTC or GMT (GMT is not technically correct, since # it *is* a timezone, but it should work for all practical purposes) if (!isUTC(x_tz)) { warning(paste0("object index class (", paste(x_tclass, collapse = ", "), ") does not support timezones.\nExpected 'UTC' timezone, but tzone is ", sQuote(x_tz)), call. = FALSE) } else { return() } } x_tz_str <- as.character(x_tz) sys_tz <- Sys.getenv("TZ") if (!is.null(x_tz) && x_tz_str != "" && !identical(sys_tz, x_tz_str)) { msg <- paste0("object timezone ('", x_tz, "') is different ", "from system timezone ('", sys_tz, "')") if (is.null(check)) { # xts_check_TZ is NULL by default # set to TRUE after messaging user how to disable the warning msg <- paste0(msg, "\n NOTE: set 'options(xts_check_TZ = FALSE)' ", "to disable this warning\n", " This note is displayed once per session") options(xts_check_TZ = TRUE) } warning(msg, call. = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/xts/R/tzone.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. naCheck <- function(x, n=0) { if(is.null(dim(x)[2])) { NAs <- .Call(C_naCheck, x, TRUE) } else NAs <- .Call(C_naCheck, rowSums(x), TRUE) ret <- list() ret$NAs <- NAs ret$nonNA <- (1+NAs):NROW(x) ret$beg <- n+NAs invisible(ret) }
/scratch/gouwar.j/cran-all/cranData/xts/R/utils.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. `write.xts` <- function(x) { NC <- NCOL(x) NR <- NROW(x) DAT <- c(NC,NR) x <- c(.index(x), as.numeric(x)) offset <- 0 for(i in 1:(NC+1)) { end <- seq(i+offset*NR, length.out=NR)-offset DAT <- c(DAT, c(x[end[1]], diff(x[end]))) offset <- offset + 1 } DAT } `read.xts` <- function(x) { NC <- x[1] NR <- x[2] x <- x[-c(1:2)] .xts(apply(matrix(x[-(1:NR)], ncol=NC),2,cumsum), cumsum(x[1:NR])) }
/scratch/gouwar.j/cran-all/cranData/xts/R/write.xts.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # xts core functions # additional methods are in correspondingly named .R files # current conversions include: # timeSeries, its, irts, ts, matrix, data.frame, and zoo # MISSING: tis, fame # # this file includes the main xts constructor as well as the reclass # function. # # xts methods (which match foreign conversion methods in other files) # are also defined below # xts() index attribute precedence should be: # 1. .index* value (e.g. .indexTZ) # backward compatibility # 2. t* value (e.g. tzone) # current function to override index attribute # 3. attribute on order.by # overridden by either 2 above # # Do we always have to override the value of an existing tzone on the index # because the default value is Sys.getenv("TZ")? # # .xts() index attribute precedence is similar. But we cannot override tclass # because it's a formal argument with a specific default. Historically .xts() # has always set the tclass to POSIXct by default, whether or not the 'index' # argument already had a tclass attribute. `xts` <- function(x=NULL, order.by=index(x), frequency=NULL, unique=TRUE, tzone=Sys.getenv("TZ"), ...) { if(is.null(x) && missing(order.by)) return(.xts(NULL, integer())) if(!timeBased(order.by)) stop("order.by requires an appropriate time-based object") #if(NROW(x) != length(order.by)) if(NROW(x) > 0 && NROW(x) != length(order.by)) stop("NROW(x) must match length(order.by)") order.by_ <- order.by # make local copy and don't change order.by if(inherits(order.by, 'Date')) { # convert to GMT POSIXct if specified order.by_ <- .POSIXct(unclass(order.by) * 86400, tz = "UTC") } if(!isOrdered(order.by_, strictly = !unique)) { indx <- order(order.by_) if(!is.null(x)) { if(NCOL(x) > 1 || is.matrix(x) || is.data.frame(x)) { x <- x[indx,,drop=FALSE] } else x <- x[indx] } order.by_ <- order.by_[indx] } if(is.null(x)) { x <- numeric(0) } else if (is.list(x)) { # list or data.frame if (is.data.frame(x)) { x <- as.matrix(x) } else { stop("cannot convert lists to xts objects") } } else if (NROW(x) > 0) { x <- as.matrix(x) } # else 'x' is a zero-length vector. Do not *add* dims via as.matrix(). # It's okay if 'x' already has dims. if(inherits(order.by, "dates")) { fmt <- "%m/%d/%y" if(inherits(order.by, "chron")) { fmt <- paste0("(", fmt, " %H:%M:%S)") } order.by_ <- strptime(as.character(order.by_), fmt) # POSIXlt } index <- as.numeric(as.POSIXct(order.by_)) if(any(!is.finite(index))) stop("'order.by' cannot contain 'NA', 'NaN', or 'Inf'") # process index attributes ctor.call <- match.call(expand.dots = TRUE) tformat. <- attr(order.by, "tformat") if(hasArg(".indexFORMAT")) { warning(sQuote(".indexFORMAT"), " is deprecated, use tformat instead.") tformat. <- eval.parent(ctor.call$.indexFORMAT) } else if(hasArg("tformat")) { tformat. <- eval.parent(ctor.call$tformat) } tclass. <- attr(order.by, "tclass") if(hasArg(".indexCLASS")) { warning(sQuote(".indexCLASS"), " is deprecated, use tclass instead.") tclass. <- eval.parent(ctor.call$.indexCLASS) } else if(hasArg("tclass")) { tclass. <- eval.parent(ctor.call$tclass) } else if(is.null(tclass.)) { tclass. <- class(order.by) if(inherits(order.by, "POSIXt")) { #tclass. <- tclass.[tclass. != "POSIXt"] } } tzone. <- tzone # default Sys.getenv("TZ") if(hasArg(".indexTZ")) { warning(sQuote(".indexTZ"), " is deprecated, use tzone instead.") tzone. <- eval.parent(ctor.call$.indexTZ) } else if(hasArg("tzone")) { tzone. <- eval.parent(ctor.call$tzone) } else { # no tzone argument if(inherits(order.by, "timeDate")) { tzone. <- order.by@FinCenter } else if(!is.null(attr(order.by, "tzone"))) { tzone. <- attr(order.by, "tzone") } } if(isClassWithoutTZ(object = order.by)) { if((hasArg(".indexTZ") || hasArg("tzone")) && !isUTC(tzone.)) { warning(paste(sQuote('tzone'),"setting ignored for ", paste(class(order.by), collapse=", "), " indexes")) } tzone. <- "UTC" # change anything in isUTC() to UTC } # xts' tzone must only contain one element (POSIXlt tzone has 3) tzone. <- tzone.[1L] x <- structure(.Data = x, index = structure(index, tzone = tzone., tclass = tclass., tformat = tformat.), class=c('xts','zoo'), ...) # remove any index attributes that came through '...' index.attr <- c(".indexFORMAT", "tformat", ".indexCLASS", "tclass", ".indexTZ", "tzone") for(iattr in index.attr) { attr(x, iattr) <- NULL } if(!is.null(attributes(x)$dimnames[[1]])) # this is very slow if user adds rownames, but maybe that is deserved :) dimnames(x) <- dimnames(x) # removes row.names x } `.xts` <- function(x=NULL, index, tclass=c("POSIXct","POSIXt"), tzone=Sys.getenv("TZ"), check=TRUE, unique=FALSE, ...) { if(check) { if( !isOrdered(index, increasing=TRUE, strictly=unique) ) stop('index is not in ',ifelse(unique, 'strictly', ''),' increasing order') } index_out <- index if(!is.numeric(index) && timeBased(index)) index_out <- as.numeric(as.POSIXct(index)) if(!is.null(x) && NROW(x) != length(index)) stop("index length must match number of observations") if(any(!is.finite(index_out))) stop("'index' cannot contain 'NA', 'NaN', or 'Inf'") if(!is.null(x)) { if(!is.matrix(x)) x <- as.matrix(x) } else if(length(x) == 0 && !is.null(x)) { x <- vector(storage.mode(x)) } else x <- numeric(0) # process index attributes ctor.call <- match.call(expand.dots = TRUE) tformat. <- attr(index, "tformat") if(hasArg(".indexFORMAT")) { warning(sQuote(".indexFORMAT"), " is deprecated, use tformat instead.") tformat. <- eval.parent(ctor.call$.indexFORMAT) } else if(hasArg("tformat")) { tformat. <- eval.parent(ctor.call$tformat) } tclass. <- tclass # default POSIXct if(hasArg(".indexCLASS")) { warning(sQuote(".indexCLASS"), " is deprecated, use tclass instead.") tclass. <- eval.parent(ctor.call$.indexCLASS) } else if(hasArg("tclass")) { tclass. <- eval.parent(ctor.call$tclass) } else { # no tclass argument tclass. <- attr(index, "tclass") if(is.null(tclass.) && timeBased(index)) { tclass. <- class(index) } else { if(!identical(tclass., c("POSIXct", "POSIXt"))) { # index argument has 'tclass' attribute but it will be ignored # FIXME: # This warning causes errors in dependencies (e.g. portfolioBacktest, # when the warning is thrown from PerformanceAnalytics). Reinstate this # warning after fixing downstream packages. # warning("the index tclass attribute is ", index.class, # " but will be changed to (POSIXct, POSIXt)") tclass. <- tclass # default POSIXct } } } tzone. <- tzone # default Sys.getenv("TZ") if(hasArg(".indexTZ")) { warning(sQuote(".indexTZ"), " is deprecated, use tzone instead.") tzone. <- eval.parent(ctor.call$.indexTZ) } else if(hasArg("tzone")) { tzone. <- eval.parent(ctor.call$tzone) } else { # no tzone argument if(inherits(index, "timeDate")) { tzone. <- index@FinCenter } else if(!is.null(attr(index, "tzone"))) { tzone. <- attr(index, "tzone") } } if(isClassWithoutTZ(object = index)) { if((hasArg(".indexTZ") || hasArg("tzone")) && !isUTC(tzone.)) { warning(paste(sQuote('tzone'),"setting ignored for ", paste(class(index), collapse=", "), " indexes")) } tzone. <- "UTC" # change anything in isUTC() to UTC } # xts' tzone must only contain one element (POSIXlt tzone has 3) tzone <- tzone[1L] xx <- .Call(C_add_xtsCoreAttributes, x, index_out, tzone., tclass., c('xts','zoo'), tformat.) # remove any index attributes that came through '...' # and set any user attributes (and/or dim, dimnames, etc) dots.names <- eval(substitute(alist(...))) if(length(dots.names) > 0L) { dot.attrs <- list(...) drop.attr <- c(".indexFORMAT", "tformat", ".indexCLASS", ".indexTZ") dot.attrs[drop.attr] <- NULL attributes(xx) <- c(attributes(xx), dot.attrs) } # ensure there are no rownames (they may have come though dimnames) rn <- dimnames(xx)[[1]] if(!is.null(rn)) { attr(xx, '.ROWNAMES') <- rn dimnames(xx)[1] <- list(NULL) } xx } `reclass` <- function(x, match.to, error=FALSE, ...) { if(!missing(match.to) && is.xts(match.to)) { if(NROW(x) != length(.index(match.to))) if(error) { stop('incompatible match.to attibutes') } else return(x) if(!is.xts(x)) { x <- .xts(coredata(x), .index(match.to), tclass = tclass(match.to), tzone = tzone(match.to), tformat = tformat(match.to)) } attr(x, ".CLASS") <- CLASS(match.to) xtsAttributes(x) <- xtsAttributes(match.to) tclass(x) <- tclass(match.to) tformat(x) <- tformat(match.to) tzone(x) <- tzone(match.to) } oldCLASS <- CLASS(x) # should this be is.null(oldCLASS)? if(length(oldCLASS) > 0 && !inherits(oldClass,'xts')) { if(!is.null(dim(x))) { if(!is.null(attr(x,'.ROWNAMES'))) { # rownames<- (i.e. dimnames<-.xts) will not set row names # force them directly attr(x, "dimnames")[[1]] <- attr(x,'.ROWNAMES')[1:NROW(x)] } } attr(x,'.ROWNAMES') <- NULL #if(is.null(attr(x,'.RECLASS')) || attr(x,'.RECLASS')) {#should it be reclassed? if(isTRUE(attr(x,'.RECLASS'))) {#should it be reclassed? #attr(x,'.RECLASS') <- NULL do.call(paste('re',oldCLASS,sep='.'),list(x)) } else { #attr(x,'.RECLASS') <- NULL x } } else { #attr(x,'.RECLASS') <- NULL x } } #`reclass` <- reclass2 `CLASS` <- function(x) { cl <- attr(x,'.CLASS') if(!is.null(cl)) { attr(cl, 'class') <- 'CLASS' return(cl) } return(NULL) } `print.CLASS` <- function(x,...) { cat(paste("previous class:",x),"\n") } `CLASS<-` <- function(x,value) { UseMethod("CLASS<-") } `CLASS<-.xts` <- function(x,value) { attr(x,".CLASS") <- value x } `is.xts` <- function(x) { inherits(x,'xts') && is.numeric(.index(x)) && !is.null(tclass(x)) } `as.xts` <- function(x,...) { UseMethod('as.xts') } #as.xts.default <- function(x, ...) x `re.xts` <- function(x,...) { # simply return the object return(x) } `as.xts.xts` <- function(x,...,.RECLASS=FALSE) { # Cannot use 'zoo()' on objects of class 'zoo' or '.CLASS' (etc.?) # Is the equivalent of a 'coredata.xts' needed? - jmu #yy <- coredata(x) #attr(yy, ".CLASS") <- NULL # using new coredata.xts method - jar if(length(x) == 0 && (!is.null(index(x)) && length(index(x))==0)) return(x) if(.RECLASS) { xx <- xts(coredata(x), order.by=index(x), .CLASS='xts', ...) } else { xx <- xts(coredata(x), order.by=index(x), ...) } xx } `xts.to.xts` <- function(x,...) { return(x) }
/scratch/gouwar.j/cran-all/cranData/xts/R/xts.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # window.xts contributed by Corwin Joy # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. .subsetTimeOfDay <- function(x, fromTimeString, toTimeString) { validateTimestring <- function(time) { h <- "(?:[01]?\\d|2[0-3])" hm <- paste0(h, "(?::?[0-5]\\d)") hms <- paste0(hm, "(?::?[0-5]\\d)") hmsS <- paste0(hms, "(?:\\.\\d{1,9})?") pattern <- paste(h, hm, hms, hmsS, sep = ")$|^(") pattern <- paste0("^(", pattern, "$)") if (!grepl(pattern, time)) { # FIXME: this isn't necessarily true... # colons aren't required, and neither are all of the components stop("Supply time-of-day subsetting in the format of T%H:%M:%OS/T%H:%M:%OS", call. = FALSE) } } validateTimestring(fromTimeString) validateTimestring(toTimeString) getTimeComponents <- function(time) { # split on decimal point time. <- strsplit(time, ".", fixed = TRUE)[[1]] hms <- time.[1L] # ensure hms string has even nchar nocolon <- gsub(":", "", hms, fixed = TRUE) if (nchar(nocolon) %% 2 > 0) { # odd nchar means leading zero is omitted from hours # all other components require zero padding hms <- paste0("0", hms) } # add colons hms <- gsub("(.{2}):?", ":\\1", hms, perl = TRUE) # remove first character (a colon) hms <- substr(hms, 2, nchar(hms)) # extract components comp <- strsplit(hms, ":", fixed = TRUE)[[1]] complist <- list(hour = comp[1L], min = comp[2L], sec = comp[3L], subsec = time.[2L]) # remove all missing components complist <- complist[!vapply(complist, is.na, logical(1))] # convert to numeric complist <- lapply(complist, as.numeric) # add timezone and return c(tz = "UTC", complist) } # first second in period (no subseconds) from <- do.call(firstof, getTimeComponents(fromTimeString)[-5L]) secBegin <- as.numeric(from) %% 86400L # last second in period to <- do.call(lastof, getTimeComponents(toTimeString)) secEnd <- as.numeric(to) %% 86400L # do subsetting tz <- tzone(x) secOfDay <- as.POSIXlt(index(x), tz = tz) secOfDay <- secOfDay$hour * 60 * 60 + secOfDay$min * 60 + secOfDay$sec if (secBegin <= secEnd) { i <- secOfDay >= secBegin & secOfDay <= secEnd } else { i <- secOfDay >= secBegin | secOfDay <= secEnd } which(i) } .subset_xts <- function(x, i, j, ...) { if(missing(i)) { i <- 1:NROW(x) } if(missing(j)) { j <- 1:NCOL(x) } .Call(C__do_subset_xts, x, i, j, FALSE) } `.subset.xts` <- `[.xts` <- function(x, i, j, drop = FALSE, which.i=FALSE,...) { USE_EXTRACT <- FALSE # initialize to FALSE dimx <- dim(x) if(is.null(dimx)) { nr <- length(x) if(nr==0 && !which.i) { idx <- index(x) if(length(idx) == 0) { # this is an empty xts object (zero-length index and no columns) # return it unchanged to match [.zoo return(x) } else { return(xts(rep(NA, length(idx)), idx)[i]) } } nr <- length(.index(x)) nc <- 1L } else { nr <- dimx[1L] nc <- dimx[2L] } if(!missing(i)) { # test for negative subscripting in i if (is.numeric(i)) { #if(any(i < 0)) { if(.Call(C_any_negative, i)) { if(!all(i <= 0)) stop('only zeros may be mixed with negative subscripts') i <- (1:nr)[i] } # check boundary; length check avoids Warning from max(), and # any_negative ensures no NA (as of r608) #if(max(i) > nr) if(length(i) > 0 && max(i) > nr) stop('subscript out of bounds') #i <- i[-which(i == 0)] } else if (timeBased(i) || (inherits(i, "AsIs") && is.character(i)) ) { # Fast binary search on set of dates i <- window_idx(x, index. = i) } else if(is.logical(i)) { i <- which(i) #(1:NROW(x))[rep(i,length.out=NROW(x))] } else if (is.character(i)) { time.of.day.pattern <- "(^/T)|(^T.*?/T)|(^T.*/$)" if (length(i) == 1 && !identical(integer(), grep(time.of.day.pattern, i[1]))) { # time of day subsetting ii <- gsub("T", "", i, fixed = TRUE) ii <- strsplit(ii, "/", fixed = TRUE)[[1L]] if (length(ii) == 1) { # i is right open ended (T.*/) ii <- c(ii, "23:59:59.999999999") } else if (nchar(ii[1L]) == 0) { # i is left open ended (/T) ii[1L] <- "00:00:00.000000000" } # else i is bounded on both sides (T.*/T.*) i <- .subsetTimeOfDay(x, ii[1L], ii[2L]) } else { # enables subsetting by date style strings # must be able to process - and then allow for operations??? i.tmp <- NULL tz <- as.character(tzone(x)) for(ii in i) { adjusted.times <- .parseISO8601(ii, .index(x)[1], .index(x)[nr], tz=tz) if(length(adjusted.times) > 1) { i.tmp <- c(i.tmp, index_bsearch(.index(x), adjusted.times$first.time, adjusted.times$last.time)) } } i <- i.tmp } i_len <- length(i) if(i_len == 1L) # IFF we are using ISO8601 subsetting USE_EXTRACT <- TRUE } if(!isOrdered(i,strictly=FALSE)) { i <- sort(i) } # subset is picky, 0's in the 'i' position cause failures zero.index <- binsearch(0L, i, FALSE) if(!is.na(zero.index)) { # at least one 0; binsearch returns location of last 0 i <- i[-(1L:zero.index)] } if(length(i) <= 0 && USE_EXTRACT) USE_EXTRACT <- FALSE if(which.i) return(i) } # if(!missing(i)) { end if (missing(j)) { if(missing(i)) i <- seq_len(nr) if(length(x)==0) { cdata <- rep(NA, length(i)) storage.mode(cdata) <- storage.mode(x) x.tmp <- .xts(cdata, .index(x)[i], tclass(x), tzone(x), dimnames = list(NULL, colnames(x))) return(x.tmp) } else { if(USE_EXTRACT) { return(.Call(C_extract_col, x, as.integer(1:nc), drop, as.integer(i[1]), as.integer(i[length(i)]))) } else { return(.Call(C__do_subset_xts, x, as.integer(i), as.integer(1:nc), drop)) } } } else # test for negative subscripting in j if (is.numeric(j)) { if(min(j,na.rm=TRUE) < 0) { if(max(j,na.rm=TRUE) > 0) stop('only zeros may be mixed with negative subscripts') j <- (1:nc)[j] } if(max(j,na.rm=TRUE) > nc) stop('subscript out of bounds') } else if(is.logical(j)) { if(length(j) == 1) { j <- (1:nc)[rep(j, nc)] } else if (length(j) > nc) { stop("(subscript) logical subscript too long") } else j <- (1:nc)[j] } else if(is.character(j)) { j <- match(j, colnames(x), nomatch=0L) # ensure all j are in colnames(x) if(any(j==0)) stop("subscript out of bounds") } j0 <- which(!as.logical(j)) if(length(j0)) j <- j[-j0] if(length(j) == 0 || (length(j)==1 && (is.na(j) || j==0))) { if(missing(i)) i <- seq_len(nr) output <- .xts(coredata(x)[i,j,drop=FALSE], .index(x)[i], tclass(x), tzone(x), class = class(x)) xtsAttributes(output) <- xtsAttributes(x) return(output) } if(missing(i)) return(.Call(C_extract_col, x, as.integer(j), drop, 1, nr)) if(USE_EXTRACT) { return(.Call(C_extract_col, x, as.integer(j), drop, as.integer(i[1]), as.integer(i[length(i)]))) } else return(.Call(C__do_subset_xts, x, as.integer(i), as.integer(j), drop)) } # Replacement method for xts objects # # Adapted from [.xts code, making use of NextGeneric as # replacement function in R already preserves all attributes # and index value is left untouched `[<-.xts` <- #`xtsreplacement` <- function(x, i, j, value) { if (!missing(i)) { i <- x[i, which.i=TRUE] } .Class <- "matrix" NextMethod(.Generic) } # Convert a character or time type to POSIXct for use by subsetting and window # We make this an explicit function so that subset and window will convert dates consistently. .toPOSIXct <- function(i, tz) { if(inherits(i, "POSIXct")) { dts <- i } else if(is.character(i)) { dts <- as.POSIXct(as.character(i),tz=tz) # Need as.character because i could be AsIs from I(dates) } else if (timeBased(i)) { if(inherits(i, "Date")) { dts <- as.POSIXct(as.character(i),tz=tz) } else { # force all other time classes to be POSIXct dts <- as.POSIXct(i,tz=tz) } } else { stop("invalid time / time based class") } dts } # find the rows of index. where the date is in [start, end]. # use binary search. # convention is that NA start or end returns empty index_bsearch <- function(index., start, end) { if(!is.null(start) && is.na(start)) return(NULL) if(!is.null(end) && is.na(end)) return(NULL) if(is.null(start)) { si <- 1 } else { si <- binsearch(start, index., TRUE) } if(is.null(end)) { ei <- length(index.) } else { ei <- binsearch(end, index., FALSE) } if(is.na(si) || is.na(ei) || si > ei) return(NULL) firstlast <- seq.int(si, ei) firstlast } # window function for xts series # return indexes in x matching dates window_idx <- function(x, index. = NULL, start = NULL, end = NULL) { if(is.null(index.)) { usr_idx <- FALSE index. <- .index(x) } else { # Translate the user index to the xts index usr_idx <- TRUE idx <- .index(x) index. <- .toPOSIXct(index., tzone(x)) index. <- unclass(index.) index. <- index.[!is.na(index.)] if(is.unsorted(index.)) { # index. must be sorted for index_bsearch # N.B!! This forces the returned values to be in ascending time order, regardless of the ordering in index, as is done in subset.xts. index. <- sort(index.) } # Fast search on index., faster than binsearch if index. is sorted (see findInterval) base_idx <- findInterval(index., idx) base_idx <- pmax(base_idx, 1L) # Only include indexes where we have an exact match in the xts series match <- idx[base_idx] == index. base_idx <- base_idx[match] index. <- index.[match] index. <- .POSIXct(index., tz = tzone(x)) if(length(base_idx) < 1) return(x[NULL,]) } if(!is.null(start)) { start <- .toPOSIXct(start, tzone(x)) } if(!is.null(end)) { end <- .toPOSIXct(end, tzone(x)) } firstlast <- index_bsearch(index., start, end) if(usr_idx && !is.null(firstlast)) { # Translate from user .index to xts index # We get back upper bound of index as per findInterval tmp <- base_idx[firstlast] res <- .Call(C_fill_window_dups_rev, tmp, .index(x)) firstlast <- rev(res) } firstlast } # window function for xts series, use binary search to be faster than base zoo function # index. defaults to the xts time index. If you use something else, it must conform to the standard for order.by in the xts constructor. # that is, index. must be time based, window.xts <- function(x, index. = NULL, start = NULL, end = NULL, ...) { # scalar NA values are treated as NULL if (isTRUE(is.na(start))) start <- NULL if (isTRUE(is.na(end))) end <- NULL if(is.null(start) && is.null(end) && is.null(index.)) return(x) # dispatch to window.zoo() for yearmon and yearqtr if(any(tclass(x) %in% c("yearmon", "yearqtr"))) { return(NextMethod(.Generic)) } firstlast <- window_idx(x, index., start, end) # firstlast may be NULL .Call(C__do_subset_xts, x, as.integer(firstlast), seq.int(1, ncol(x)), drop = FALSE) } # Declare binsearch to call the routine in binsearch.c binsearch <- function(key, vec, start=TRUE) { # Convert to double if both are not integer if (storage.mode(key) != storage.mode(vec)) { storage.mode(key) <- storage.mode(vec) <- "double" } .Call(C_binsearch, key, vec, start) } # Unit tests for the above code may be found in runit.xts.methods.R
/scratch/gouwar.j/cran-all/cranData/xts/R/xts.methods.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. xtsible <- function(x) { if(inherits(try(as.xts(x),silent=TRUE),'try-error')) { FALSE } else TRUE } use.xts <- try.xts <- function(x, ..., error=TRUE) { if(is.xts(x)) { #attr(x,'.RECLASS') <- FALSE return(x) } xx <- try(as.xts(x,..., .RECLASS=TRUE),silent=TRUE) if(inherits(xx,'try-error')) { if(is.character(error)) { stop(error) } else if(is.function(error)) { return(error(x, ...)) } else if(error) { stop(gsub('\n','',xx)) } else { return(x) } } else { # made positive: now test if needs to be reclassed structure(xx, .RECLASS=TRUE) } } .merge.xts.scalar <- function(x, length.out, ...) { if( length.out == 0) return(vector(storage.mode(x), 0)) if( length(x) == 1 ) return(matrix(rep(x, length.out=length.out))) if( NROW(x) == length.out ) return(x) stop("improper length of one or more arguments to merge.xts") } use.reclass <- Reclass <- function(x) { xx <- match.call() xxObj <- eval.parent(parse(text=all.vars(xx)[1]), 1) inObj <- try.xts(xxObj, error=FALSE) xx <- eval(match.call()[[-1]]) reclass(xx, inObj) }
/scratch/gouwar.j/cran-all/cranData/xts/R/xtsible.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. as.xts.yearmon <- function(x, ...) { xts(x=NULL, order.by=x) } as.xts.yearqtr <- function(x, ...) { xts(x=NULL, order.by=x) }
/scratch/gouwar.j/cran-all/cranData/xts/R/yearmon.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # functions to handle zoo <--> xts conversions `re.zoo` <- function(x,...) { xx <- coredata(x) xx <- zoo(xx, order.by=index(x), ...) if(length(dimnames(x)[[2]]) < 2) { dimnames(xx) <- NULL dim(xx) <- NULL attr(xx,'names') <- as.character(index(x)) } xx } `as.xts.zoo` <- function(x,order.by=index(x),frequency=NULL,...,.RECLASS=FALSE) { if(.RECLASS) { xx <- xts(coredata(x), # Cannot use 'zoo()' on objects of class 'zoo' - jmu order.by=order.by, frequency=frequency, .CLASS='zoo', ...) } else { xx <- xts(coredata(x), # Cannot use 'zoo()' on objects of class 'zoo' - jmu order.by=order.by, frequency=frequency, ...) } # # if(!is.null(attr(x,'names'))) { # dim(xx) <- c(NROW(xx),NCOL(xx)) # dn <- list(attr(x,'names'),colnames(x)) # dimnames(xx) <- dn # attr(xx,'.ROWNAMES') <- attr(x,'names') # } # xx } `as.zoo.xts` <- function(x,...) { cd <- coredata(x); if( length(cd)==0 ) cd <- NULL zoo(cd, order.by=index(x), ...) }
/scratch/gouwar.j/cran-all/cranData/xts/R/zoo.R
# # xts: eXtensible time-series # # Copyright (C) 2008 Jeffrey A. Ryan jeff.a.ryan @ gmail.com # # Contributions from Joshua M. Ulrich # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # internal package environment for use with lines.xts # Do we still need this env? .xtsEnv <- new.env() # Environment for our xts chart objects (xts_chob) .plotxtsEnv <- new.env() register_s3_method <- function(pkg, generic, class, fun = NULL) { stopifnot(is.character(pkg), length(pkg) == 1L) stopifnot(is.character(generic), length(generic) == 1L) stopifnot(is.character(class), length(class) == 1L) if (is.null(fun)) { fun <- get(paste0(generic, ".", class), envir = parent.frame()) } else { stopifnot(is.function(fun)) } if (isNamespaceLoaded(pkg)) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } # Always register hook in case package is later unloaded & reloaded setHook( packageEvent(pkg, "onLoad"), function(...) { registerS3method(generic, class, fun, envir = asNamespace(pkg)) } ) } .onAttach <- function(libname, pkgname) { warn_dplyr_lag <- getOption("xts.warn_dplyr_breaks_lag", TRUE) dplyr_will_mask_lag <- conflictRules("dplyr") if (is.null(dplyr_will_mask_lag)) { dplyr_will_mask_lag <- TRUE } else { dplyr_will_mask_lag <- all(dplyr_will_mask_lag$exclude != "lag") } if (warn_dplyr_lag && dplyr_will_mask_lag) { ugly_message <- " ######################### Warning from 'xts' package ########################## # # # The dplyr lag() function breaks how base R's lag() function is supposed to # # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or # # source() into this session won't work correctly. # # # # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add # # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop # # dplyr from breaking base R's lag() function. # # # # Code in packages is not affected. It's protected by R's namespace mechanism # # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. # # # ###############################################################################" if ("package:dplyr" %in% search()) { packageStartupMessage(ugly_message) } else { setHook(packageEvent("dplyr", "attach"), function(...) packageStartupMessage(ugly_message)) } } } .onLoad <- function(libname, pkgname) { # if(Sys.getenv("TZ") == "") { # packageStartupMessage("xts now requires a valid TZ environment variable to be set") # packageStartupMessage(" no TZ var is set, setting to TZ=GMT") # Sys.setenv(TZ="GMT") # } else { # packageStartupMessage("xts now requires a valid TZ environment variable to be set") # packageStartupMessage(" your current TZ:",paste(Sys.getenv("TZ"))) # } if (getRversion() < "3.6.0") { register_s3_method("timeSeries", "as.timeSeries", "xts") if (utils::packageVersion("zoo") < "1.8.5") { # xts:::as.zoo.xts was copied to zoo:::as.zoo.xts in zoo 1.8-5 register_s3_method("zoo", "as.zoo", "xts") } } invisible() } .onUnload <- function(libpath) { library.dynam.unload("xts", libpath) } if(getRversion() < "2.11.0") { .POSIXct <- function(xx, tz = NULL) structure(xx, class = c("POSIXct", "POSIXt"), tzone = tz) }
/scratch/gouwar.j/cran-all/cranData/xts/R/zzz.R
# R function to call your compiled code checkOrder <- function(x) { .Call('check_order', x, TRUE, TRUE) }
/scratch/gouwar.j/cran-all/cranData/xts/inst/api_example/R/checkOrder.R
stopifnot(require("xts")) stopifnot(require("microbenchmark")) # Benchmark [.xts using ISO8601 range on large objects N <- 2e7 s <- 86400*365.25 x <- .xts(1:N, 1.0*seq(s*20, s*40, length.out = N), tzone = "UTC") # warmup, in case there's any JIT for (i in 1:2) { x["1999/2001",] } profile <- FALSE if (profile) { # Use loop if profiling, so microbenchmark calls aren't included Rprof(line.profiling = TRUE) for(i in 1:10) { x[rng,] } Rprof(NULL) print(srp <- summaryRprof()) } else { cat("Subset using ISO-8601 range\n") microbenchmark(x["1990",], x["1990/",], x["/2009",], x["1990/1994",], x["1990/1999",], x["1990/2009",], times = 5) } cat("Subset using integer vector\n") i001 <- seq(1, N, 1) i005 <- seq(1, N, 5) i010 <- seq(1, N, 10) i050 <- seq(1, N, 50) i100 <- seq(1, N, 100) microbenchmark(x[i001,], x[i005,], x[i010,], x[i050,], x[i100,], times = 5) cat("Subset using logical vector\n") l001 <- l005 <- l010 <- l050 <- l100 <- logical(N) l001[i001] <- TRUE l005[i005] <- TRUE l010[i010] <- TRUE l050[i050] <- TRUE l100[i100] <- TRUE microbenchmark(x[l001,], x[l005,], x[l010,], x[l050,], x[l100,], times = 5) cat("Subset using date-time vector\n") t001 <- index(x)[i001] t005 <- index(x)[i005] t010 <- index(x)[i010] t050 <- index(x)[i050] t100 <- index(x)[i100] microbenchmark(x[t001,], x[t005,], x[t010,], x[t050,], x[t100,], times = 5)
/scratch/gouwar.j/cran-all/cranData/xts/inst/benchmarks/benchmark.subset.R
### R code from vignette source 'xts-faq.Rnw' ################################################### ### code chunk number 1: preliminaries ################################################### library("xts") Sys.setenv(TZ="GMT") ################################################### ### code chunk number 2: xts-faq.Rnw:88-90 (eval = FALSE) ################################################### ## filenames <- c("a.csv", "b.csv", "c.csv") ## sample.xts <- as.xts(do.call("rbind", lapply(filenames, read.zoo))) ################################################### ### code chunk number 3: xts-faq.Rnw:106-107 (eval = FALSE) ################################################### ## lm(sample.xts[, "Res"] ~ sample.xts[, "ThisVar"] + sample.xts[, "ThatVar"]) ################################################### ### code chunk number 4: xts-faq.Rnw:110-111 (eval = FALSE) ################################################### ## with(sample.xts, lm(Res ~ ThisVar + ThatVar)) ################################################### ### code chunk number 5: xts-faq.Rnw:118-121 ################################################### sample.xts <- xts(c(1:3, 0, 0, 0), as.POSIXct("1970-01-01")+0:5) sample.xts[sample.xts==0] <- NA cbind(orig=sample.xts, locf=na.locf(sample.xts)) ################################################### ### code chunk number 6: xts-faq.Rnw:128-130 ################################################### data(sample_matrix) sample.xts <- xts(1:10, seq(as.POSIXct("1970-01-01"), by=0.1, length=10)) ################################################### ### code chunk number 7: xts-faq.Rnw:138-140 ################################################### options(digits.secs=3) head(sample.xts) ################################################### ### code chunk number 8: xts-faq.Rnw:151-154 ################################################### dt <- as.POSIXct("2012-03-20 09:02:50.001") print(as.numeric(dt), digits=20) sprintf("%20.10f", dt) ################################################### ### code chunk number 9: xts-faq.Rnw:163-164 (eval = FALSE) ################################################### ## sample.xts.2 <- xts(t(apply(sample.xts, 1, myfun)), index(sample.xts)) ################################################### ### code chunk number 10: xts-faq.Rnw:172-177 ################################################### sample.xts <- xts(1:50, seq(as.POSIXct("1970-01-01"), as.POSIXct("1970-01-03")-1, length=50)) apply.daily(sample.xts, colMeans) period.apply(sample.xts, endpoints(sample.xts, "days"), colMeans) period.apply(sample.xts, endpoints(sample.xts, "hours", 6), colMeans) ################################################### ### code chunk number 11: xts-faq.Rnw:185-186 (eval = FALSE) ################################################### ## apply.daily(sample.xts['T06:00/T17:00',], colMeans) ################################################### ### code chunk number 12: xts-faq.Rnw:196-209 ################################################### sample.xts <- xts(1:6, as.POSIXct(c("2009-09-22 07:43:30", "2009-10-01 03:50:30", "2009-10-01 08:45:00", "2009-10-01 09:48:15", "2009-11-11 10:30:30", "2009-11-11 11:12:45"))) # align index into regular (e.g. 3-hour) blocks aligned.xts <- align.time(sample.xts, n=60*60*3) # apply your function to each block count <- period.apply(aligned.xts, endpoints(aligned.xts, "hours", 3), length) # create an empty xts object with the desired regular index empty.xts <- xts(, seq(start(aligned.xts), end(aligned.xts), by="3 hours")) # merge the counts with the empty object head(out1 <- merge(empty.xts, count)) # or fill with zeros head(out2 <- merge(empty.xts, count, fill=0)) ################################################### ### code chunk number 13: xts-faq.Rnw:219-220 (eval = FALSE) ################################################### ## sample.xts <- as.xts(transform(sample.xts, ABC=1)) ################################################### ### code chunk number 14: xts-faq.Rnw:224-225 (eval = FALSE) ################################################### ## tzone(sample.xts) <- Sys.getenv("TZ") ################################################### ### code chunk number 15: xts-faq.Rnw:237-238 (eval = FALSE) ################################################### ## sample.xts[sample.xts$Symbol == "AAPL" & index(sample.xts) == as.POSIXct("2011-09-21"),] ################################################### ### code chunk number 16: xts-faq.Rnw:241-242 (eval = FALSE) ################################################### ## sample.xts[sample.xts$Symbol == "AAPL"]['2011-09-21'] ################################################### ### code chunk number 17: xts-faq.Rnw:249-253 ################################################### data(sample_matrix) sample.xts <- as.xts(sample_matrix) wday.xts <- sample.xts[.indexwday(sample.xts) %in% 1:5] head(wday.xts) ################################################### ### code chunk number 18: xts-faq.Rnw:266-268 ################################################### Data <- data.frame(timestamp=as.Date("1970-01-01"), obs=21) sample.xts <- xts(Data[,-1], order.by=Data[,1]) ################################################### ### code chunk number 19: xts-faq.Rnw:272-275 ################################################### Data <- data.frame(obs=21, timestamp=as.Date("1970-01-01")) sample.xts <- xts(Data[,!grepl("timestamp",colnames(Data))], order.by=Data$timestamp) ################################################### ### code chunk number 20: xts-faq.Rnw:288-291 (eval = FALSE) ################################################### ## x1 <- align.time(xts(Data1$obs, Data1$timestamp), n=600) ## x2 <- align.time(xts(Data2$obs, Data2$timestamp), n=600) ## merge(x1, x2) ################################################### ### code chunk number 21: xts-faq.Rnw:295-301 ################################################### data(sample_matrix) sample.xts <- as.xts(sample_matrix) sample.xts["2007-01"]$Close <- sample.xts["2007-01"]$Close + 1 #Warning message: #In NextMethod(.Generic) : # number of items to replace is not a multiple of replacement length ################################################### ### code chunk number 22: xts-faq.Rnw:314-315 (eval = FALSE) ################################################### ## sample.xts["2007-01",]$Close <- sample.xts["2007-01"]$Close + 1 ################################################### ### code chunk number 23: xts-faq.Rnw:323-324 (eval = FALSE) ################################################### ## sample.xts["2007-01","Close"] <- sample.xts["2007-01","Close"] + 1
/scratch/gouwar.j/cran-all/cranData/xts/inst/doc/xts-faq.R
### R code from vignette source 'xts.Rnw' ################################################### ### code chunk number 1: a ################################################### require(xts) data(sample_matrix) class(sample_matrix) str(sample_matrix) matrix_xts <- as.xts(sample_matrix,dateFormat='Date') str(matrix_xts) df_xts <- as.xts(as.data.frame(sample_matrix), important='very important info!') str(df_xts) ################################################### ### code chunk number 2: xtsconstructor ################################################### xts(1:10, Sys.Date()+1:10) ################################################### ### code chunk number 3: xtsmethods (eval = FALSE) ################################################### ## matrix_xts['2007-03'] ################################################### ### code chunk number 4: xtsmethods-hidden ################################################### head(matrix_xts['2007-03'],5) cat('...\n') ################################################### ### code chunk number 5: xtsmethods2 (eval = FALSE) ################################################### ## matrix_xts['/2007-01-07'] ################################################### ### code chunk number 6: xtsmethods2-hidden ################################################### matrix_xts['/2007-01-07'] ################################################### ### code chunk number 7: xtsfirstandlast (eval = FALSE) ################################################### ## first(matrix_xts,'1 week') ################################################### ### code chunk number 8: xtsfirstandlast-hidden ################################################### head(first(matrix_xts,'1 week')) ################################################### ### code chunk number 9: xtsfirstandlast2 ################################################### first(last(matrix_xts,'1 week'),'3 days') ################################################### ### code chunk number 10: tclass ################################################### tclass(matrix_xts) tclass(convertIndex(matrix_xts,'POSIXct')) ################################################### ### code chunk number 11: xtsaxTicksByTime ################################################### axTicksByTime(matrix_xts, ticks.on='months') ################################################### ### code chunk number 12: xtsplot ################################################### plot(matrix_xts[,1],major.ticks='months',minor.ticks=FALSE,main=NULL,col=3) ################################################### ### code chunk number 13: asxtsreclass ################################################### # using xts-style subsetting doesn't work on non-xts objects sample_matrix['2007-06'] # convert to xts to use time-based subsetting str(as.xts(sample_matrix)['2007-06']) # reclass to get to original class back str(reclass(as.xts(sample_matrix)['2007-06'])) ################################################### ### code chunk number 14: usereclass ################################################### z <- zoo(1:10,Sys.Date()+1:10) # filter converts to a ts object - and loses the zoo class (zf <- filter(z, 0.2)) class(zf) # using Reclass, the zoo class is preserved (zf <- Reclass(filter(z, 0.2))) class(zf) ################################################### ### code chunk number 15: periodicity ################################################### periodicity(matrix_xts) ################################################### ### code chunk number 16: endpoints ################################################### endpoints(matrix_xts,on='months') endpoints(matrix_xts,on='weeks') ################################################### ### code chunk number 17: toperiod ################################################### to.period(matrix_xts,'months') periodicity(to.period(matrix_xts,'months')) # changing the index to something more appropriate to.monthly(matrix_xts) ################################################### ### code chunk number 18: periodapply ################################################### # the general function, internally calls sapply period.apply(matrix_xts[,4],INDEX=endpoints(matrix_xts),FUN=max) ################################################### ### code chunk number 19: applymonthly ################################################### # same result as above, just a monthly interface apply.monthly(matrix_xts[,4],FUN=max) ################################################### ### code chunk number 20: periodsum ################################################### # using one of the optimized functions - about 4x faster period.max(matrix_xts[,4], endpoints(matrix_xts)) ################################################### ### code chunk number 21: devtryxts ################################################### period.apply ################################################### ### code chunk number 22: attributes ################################################### str(attributes(matrix_xts)) str(xtsAttributes(matrix_xts)) # attach some attributes xtsAttributes(matrix_xts) <- list(myattr="my meta comment") attr(matrix_xts, 'another.item') <- "one more thing..." str(attributes(matrix_xts)) str(xtsAttributes(matrix_xts)) ################################################### ### code chunk number 23: subclass ################################################### xtssubclass <- structure(matrix_xts, class=c('xts2','xts','zoo')) class(xtssubclass)
/scratch/gouwar.j/cran-all/cranData/xts/inst/doc/xts.R
test.rowSums_dispatch <- function() { x <- xts(cbind(1:3, 4:6), .Date(1:3)) y <- xts(base::rowSums(x), index(x)) checkEqualsNumeric(y, rowSums(x)) checkEquals(index(y), index(x)) d <- data.frame(x) v <- as.vector(y) checkEqualsNumeric(v, rowSums(d)) checkEquals(rownames(d), as.character(index(x))) } test.rowMeans_dispatch <- function() { x <- xts(cbind(1:3, 4:6), .Date(1:3)) y <- xts(base::rowMeans(x), index(x)) checkEqualsNumeric(y, rowMeans(x)) checkEquals(index(y), index(x)) d <- data.frame(x) v <- as.vector(y) checkEqualsNumeric(v, rowMeans(d)) checkEquals(rownames(d), as.character(index(x))) }
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/runit.rowSums-rowMeans.R
all.modes <- c("double", "integer", "logical", "character") ops.math <- c("+", "-", "*", "/", "^", "%%", "%/%") ops.relation <- c(">", ">=", "==", "!=", "<=", "<") ops.logic <- c("&", "|", ops.relation) all.ops <- c(ops.math, ops.logic) ops_numeric_tester <- function(e1, e2, mode, op) { storage.mode(e1) <- mode storage.mode(e2) <- mode eval(call(op, e1, e2)) } make_msg <- function(info, op, type) { sprintf("%s op: %s, type: %s", info, op, type) } ### {{{ 2-column objects info_msg <- "test.ops_xts2d_matrix2d_dimnames" X1 <- .xts(cbind(1:3, 4:6), 1:3, dimnames = list(NULL, c("x", "y"))) M1 <- as.matrix(X1) * 5 M2 <- M1 colnames(M2) <- rev(colnames(M2)) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(M2, X1, m, o) E <- X1 colnames(E) <- colnames(M2) E[] <- ops_numeric_tester(M2, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts2d_matrix2d_only_colnames" X1 <- .xts(cbind(1:3, 4:6), 1:3, dimnames = list(NULL, c("x", "y"))) M1 <- coredata(X1) * 5 M2 <- M1 colnames(M2) <- rev(colnames(M2)) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(M2, X1, m, o) E <- X1 colnames(E) <- colnames(M2) E[] <- ops_numeric_tester(M2, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts2d_matrix2d_only_rownames" X1 <- .xts(cbind(1:3, 4:6), 1:3) M1 <- coredata(X1) * 5 rownames(M1) <- format(.POSIXct(1:3)) M2 <- M1 colnames(M2) <- rev(colnames(M2)) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(M2, X1, m, o) E <- X1 colnames(E) <- colnames(M2) E[] <- ops_numeric_tester(M2, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts2d_matrix2d_no_dimnames" X1 <- .xts(cbind(1:3, 1:3), 1:3) M1 <- coredata(X1) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(M1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(M1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } ### }}} 2-column objects ### {{{ 1-column objects info_msg <- "test.ops_xts1d_matrix1d_dimnames" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) M1 <- as.matrix(X1) * 5 M2 <- M1 colnames(M2) <- "y" for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(M2, X1, m, o) E <- X1 E[] <- ops_numeric_tester(M2, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" colnames(E) <- "y" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_matrix1d_only_colnames" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) M1 <- coredata(X1) * 5 M2 <- M1 colnames(M2) <- "y" for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(M2, X1, m, o) E <- X1 E[] <- ops_numeric_tester(M2, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" colnames(E) <- "y" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_matrix1d_only_rownames" X1 <- .xts(1:3, 1:3) M1 <- coredata(X1) * 5 rownames(M1) <- format(.POSIXct(1:3)) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(M1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(M1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_matrix1d_no_dimnames" X1 <- .xts(1:3, 1:3) M1 <- coredata(X1) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(M1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(M1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_xts1d" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(X1), coredata(X1), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_xts1d_different_index" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) X2 <- .xts(2:4, 2:4, dimnames = list(NULL, "y")) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, X2, m, o) E <- X1[2:3,] E[] <- ops_numeric_tester(coredata(E), coredata(X2[1:2,]), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments should only change column names e <- ops_numeric_tester(X2, X1, m, o) E <- X2[1:2,] E[] <- ops_numeric_tester(coredata(X1[2:3,]), coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } ### }}} 1-column objects ### {{{ xts with dim, vector info_msg <- "test.ops_xts2d_vector_no_names" X1 <- .xts(cbind(1:3, 4:6), 1:3, dimnames = list(NULL, c("x", "y"))) V1 <- as.vector(coredata(X1[,1L])) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, V1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), V1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(V1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(V1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts2d_vector_names" X1 <- .xts(cbind(1:3, 4:6), 1:3, dimnames = list(NULL, c("x", "y"))) V1 <- setNames(as.vector(X1[,1L]), index(X1)) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, V1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), V1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(V1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(V1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_vector_no_names" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) V1 <- as.vector(coredata(X1[,1L])) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, V1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), V1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(V1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(V1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts1d_vector_names" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) V1 <- setNames(as.vector(X1[,1L]), index(X1)) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(X1, V1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(E), V1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(V1, X1, m, o) E <- X1 E[] <- ops_numeric_tester(V1, coredata(E), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } ### }}} xts with dim, vector ### {{{ xts no dims, matrix/vector info_msg <- "test.ops_xts_no_dim_matrix1d" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) Xv <- drop(X1) M1 <- coredata(X1) * 5 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(Xv, M1, m, o) E <- X1 E[] <- ops_numeric_tester(coredata(Xv), M1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(M1, Xv, m, o) E <- X1 E[] <- ops_numeric_tester(M1, coredata(Xv), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts_no_dim_matrix2d" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) Xv <- drop(X1) X2 <- merge(x = Xv * 2, y = Xv * 5) M2 <- coredata(X2) for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(Xv, M2, m, o) E <- X2 E[] <- ops_numeric_tester(coredata(Xv), M2, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" # results no identical because attributes change order expect_equal(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(M2, Xv, m, o) E <- X2 E[] <- ops_numeric_tester(M2, coredata(Xv), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" # results no identical because attributes change order expect_equal(e, E, info = make_msg(info_msg, o, m)) } } info_msg <- "test.ops_xts_no_dim_vector" X1 <- .xts(1:3, 1:3, dimnames = list(NULL, "x")) Xv <- drop(X1) V1 <- 4:6 for (o in all.ops) { for (m in all.modes) { if ("character" == m && !(o %in% ops.relation)) next e <- ops_numeric_tester(Xv, V1, m, o) E <- Xv E[] <- ops_numeric_tester(coredata(Xv), V1, m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) # order of arguments shouldn't matter e <- ops_numeric_tester(V1, Xv, m, o) E <- Xv E[] <- ops_numeric_tester(V1, coredata(Xv), m, o) if (o %in% ops.logic) storage.mode(E) <- "logical" expect_identical(e, E, info = make_msg(info_msg, o, m)) } } ### }}} xts vector, matrix/vector ### These tests check that the time class of a time series on which ### a relational operator is applied is not changed. ts1 <- xts(17, order.by = as.Date('2020-01-29')) info_msg <- "test.get_tclass_ts1" expect_identical(tclass(ts1), c("Date"), info = info_msg) info_msg <- "test.tclass_after_rel_op" expect_identical(tclass(ts1 < 0), c("Date"), info = paste(info_msg, "| <")) expect_identical(tclass(ts1 > 0), c("Date"), info = paste(info_msg, "| >")) expect_identical(tclass(ts1 <= 0), c("Date"), info = paste(info_msg, "| <=")) expect_identical(tclass(ts1 >= 0), c("Date"), info = paste(info_msg, "| >=")) expect_identical(tclass(ts1 == 0), c("Date"), info = paste(info_msg, "| ==")) expect_identical(tclass(ts1 != 0), c("Date"), info = paste(info_msg, "| !=")) tstz <- "Atlantic/Reykjavik" ts2 <- xts(17, order.by = as.POSIXct("2020-01-29", tz = tstz)) info_msg <- "test.get_tclass_POSIXct_ts2" expect_true("POSIXct" %in% tclass(ts2), info = info_msg) info_msg <- "test.tclass_POSIXct_after_rel_op" expect_true("POSIXct" %in% tclass(ts2 < 0), info = paste(info_msg, "| <")) expect_true("POSIXct" %in% tclass(ts2 > 0), info = paste(info_msg, "| >")) expect_true("POSIXct" %in% tclass(ts2 <= 0), info = paste(info_msg, "| <=")) expect_true("POSIXct" %in% tclass(ts2 >= 0), info = paste(info_msg, "| >=")) expect_true("POSIXct" %in% tclass(ts2 == 0), info = paste(info_msg, "| ==")) expect_true("POSIXct" %in% tclass(ts2 != 0), info = paste(info_msg, "| !=")) info_msg <- "test.get_tzone_ts2" expect_identical(tzone(ts2), tstz, info = info_msg) info_msg <- "test.tzone_after_rel_op" expect_identical(tzone(ts2 < 0), tstz, info = paste(info_msg, "| <")) expect_identical(tzone(ts2 > 0), tstz, info = paste(info_msg, "| >")) expect_identical(tzone(ts2 <= 0), tstz, info = paste(info_msg, "| <=")) expect_identical(tzone(ts2 >= 0), tstz, info = paste(info_msg, "| >=")) expect_identical(tzone(ts2 == 0), tstz, info = paste(info_msg, "| ==")) expect_identical(tzone(ts2 != 0), tstz, info = paste(info_msg, "| !=")) ### Ops.xts() doesn't change column names x <- .xts(1:3, 1:3, dimnames = list(NULL, c("-1"))) z <- as.zoo(x) expect_equal(names(x + x[-1,]), names(z + z[-1,]), "Ops.xts() doesn't change column names when merge() is called") expect_equal(names(x + x), names(z + z), "Ops.xts() doesn't change column names when indexes are equal") ### Ops.xts returns derived class st <- Sys.time() x1 <- xts(1, st) x2 <- xts(2, st) x3 <- xts(3, st) # regular xts object # derived class objects klass <- c("foo", "xts", "zoo") class(x1) <- klass class(x2) <- klass expect_identical(klass, class(x1 + x2), "Ops.xts('foo', 'foo') returns derived class") expect_identical(klass, class(x2 + x1), "Ops.xts('foo', 'foo') returns derived class") expect_identical(klass, class(x1 + x3), "Ops.xts('foo', 'xts') returns derived class") expect_identical(class(x3), class(x3 + x1), "Ops.xts('xts', 'foo') returns xts class") info_msg <- "test.Ops.xts_unary" xpos <- xts(1, .Date(1)) xneg <- xts(-1, .Date(1)) lt <- xts(TRUE, .Date(1)) lf <- xts(FALSE, .Date(1)) expect_identical(xpos, +xpos, info = paste(info_msg, "+ positive xts")) expect_identical(xneg, +xneg, info = paste(info_msg, "+ negative xts")) expect_identical(xneg, -xpos, info = paste(info_msg, "- positive xts")) expect_identical(xpos, -xneg, info = paste(info_msg, "- negative xts")) expect_identical(lf, !lt, info = paste(info_msg, "! TRUE")) expect_identical(lt, !lf, info = paste(info_msg, "! FALSE"))
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-Ops.R
# make.index.unique info_msg <- "make.index.unique() uses 1 microsecond epsilon by default" x <- .xts(1:5, rep(1e-6, 5)) y <- make.index.unique(x) expect_equivalent(target = cumsum(rep(1e-6, 5)), current = .index(y), info = info_msg) info_msg <- "make.index.unique() warns when index value will be overwritten" x <- .xts(1:5, c(rep(1e-6, 4), 3e-6)) expect_warning(make.index.unique(x, eps = 1e-6), pattern = "index value is unique but will be replaced", info = info_msg) info_msg <- "make.index.unique() returns unique and sorted index" expect_equivalent(target = cumsum(rep(1e-6, 5)), current = .index(y), info = info_msg) info_msg <- "test.make.index.unique_adds_eps_to_duplicates" epsilon <- c(1e-6, 1e-7, 1e-8) for (eps in epsilon) { x <- .xts(1:5, rep(eps, 5)) y <- make.index.unique(x, eps = eps) expect_equivalent(target = .index(y), current = cumsum(rep(eps, 5)), info = info_msg) } info_msg <- "test.make.index.unique_no_warn_if_unique_timestamps_unchanged" x <- .xts(1:10, c(rep(1e-6, 9), 1e-5)) y <- make.index.unique(x, eps = 1e-6) expect_equivalent(target = .index(y), current = cumsum(rep(1e-6, 10)), info = info_msg) # There should be a warning if the cumulative epsilon for a set of duplicate # index values is larger than the first unique index value that follows. # When this happens, we will overwrite that non-duplicate index value with # the prior index value + eps. info_msg <- "test.make.index.unique_warns_if_unique_timestamp_changes" x <- .xts(1:5, c(rep(0, 4), 2e-6)) expect_warning(make.index.unique(x, eps = 1e-6)) # There should be a warning if the cumulative epsilon for a set of duplicate # index values is larger than the first unique index value that follows. # When this happens, we will overwrite that non-duplicate index value with # the prior index value + eps. info_msg <- "test.make.index.unique_warns_ONCE_if_unique_timestamp_changes" x <- .xts(1:5, c(rep(0, 3), 2, 3) * 1e-6) count <- 0L expect_warning(make.index.unique(x, eps = 1e-6)) info_msg <- "test.make.index.unique_converts_date_index_to_POSIXct" # It doesn't make sense to add a small epsilon to a date index. The C code # converts the integer index to a double, but it keeps the same index class. # The index class should be converted to POSIXct.
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-align.time.R
# ensure xts objects with index attributes attached are equal to # xts objects with index attributes on the index only info_msg <- "test.attr_on_object_equal_to_attr_on_index" attrOnObj <- structure(1:3, index = structure(1:3, tzone = "UTC", tclass = "Date"), class = c("xts", "zoo"), dim = c(3L, 1L), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", dimnames = list(NULL, "x")) attrOnIndex <- structure(1:3, index = structure(1:3, tzone = "UTC", tclass = "Date"), class = c("xts", "zoo"), dim = c(3L, 1L), dimnames = list(NULL, "x")) expect_equal(target = attrOnIndex, current = attrOnObj, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-all.equal.R
na <- NA_integer_ # vector with even length, odd length # no/yes result (potential infinite loop) # https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/ info_msg <- "integer predicate no yes stops" ans <- 2L ivec <- 3:4 ikey <- ivec[ans] expect_identical(ans, xts:::binsearch(ikey, ivec, TRUE), paste(info_msg, TRUE)) expect_identical(ans, xts:::binsearch(ikey, ivec, FALSE), paste(info_msg, FALSE)) # small steps between vector elements (test that we actually stop) info_msg <- "test.double_with_small_delta_stops" ans <- 10L dvec <- 1 + (-10:10 / 1e8) dkey <- dvec[ans] expect_identical(ans, xts:::binsearch(dkey, dvec, TRUE)) expect_identical(ans, xts:::binsearch(dkey, dvec, FALSE)) info_msg <- "test.find_first_zero_even_length" ivec <- sort(c(0L, -3:5L)) dvec <- ivec * 1.0 expect_identical(4L, xts:::binsearch(0L, ivec, TRUE)) expect_identical(4L, xts:::binsearch(0.0, dvec, TRUE)) info_msg <- "test.find_last_zero_even_length" ivec <- sort(c(0L, -3:5L)) dvec <- ivec * 1.0 expect_identical(5L, xts:::binsearch(0L, ivec, FALSE)) expect_identical(5L, xts:::binsearch(0.0, dvec, FALSE)) info_msg <- "test.find_first_zero_odd_length" ivec <- sort(c(0L, -3:5L)) dvec <- ivec * 1.0 expect_identical(4L, xts:::binsearch(0L, ivec, TRUE)) expect_identical(4L, xts:::binsearch(0.0, dvec, TRUE)) info_msg <- "test.find_last_zero_odd_length" ivec <- sort(c(0L, -3:5L)) dvec <- ivec * 1.0 expect_identical(5L, xts:::binsearch(0L, ivec, FALSE)) expect_identical(5L, xts:::binsearch(0.0, dvec, FALSE)) # key is outside of vector info_msg <- "test.key_less_than_min" ivec <- 1:6 expect_identical(1L, xts:::binsearch(-9L, ivec, TRUE)) expect_identical(na, xts:::binsearch(-9L, ivec, FALSE)) dvec <- ivec * 1.0 expect_identical(1L, xts:::binsearch(-9, dvec, TRUE)) expect_identical(na, xts:::binsearch(-9, dvec, FALSE)) info_msg <- "test.key_greater_than_max" ivec <- 1:6 expect_identical(na, xts:::binsearch( 9L, ivec, TRUE)) expect_identical(6L, xts:::binsearch( 9L, ivec, FALSE)) dvec <- ivec * 1.0 expect_identical(na, xts:::binsearch( 9, dvec, TRUE)) expect_identical(6L, xts:::binsearch( 9, dvec, FALSE)) # key is NA info_msg <- "test.key_is_NA" ivec <- 1:6 ikey <- NA_integer_ expect_identical(na, xts:::binsearch(ikey, ivec, TRUE)) expect_identical(na, xts:::binsearch(ikey, ivec, FALSE)) dvec <- ivec * 1.0 dkey <- NA_real_ expect_identical(na, xts:::binsearch(dkey, dvec, TRUE)) expect_identical(na, xts:::binsearch(dkey, dvec, FALSE)) # key is zero-length info_msg <- "test.key_is_zero_length" # have empty key return NA ivec <- 1:6 ikey <- integer() expect_identical(na, xts:::binsearch(ikey, ivec, TRUE)) expect_identical(na, xts:::binsearch(ikey, ivec, FALSE)) dvec <- ivec * 1.0 dkey <- double() expect_identical(na, xts:::binsearch(dkey, dvec, TRUE)) expect_identical(na, xts:::binsearch(dkey, dvec, FALSE)) # vec is zero-length info_msg <- "test.vec_is_zero_length" # have empty vector return NA ivec <- integer() ikey <- 0L expect_identical(na, xts:::binsearch(ikey, ivec, TRUE)) expect_identical(na, xts:::binsearch(ikey, ivec, FALSE)) dvec <- double() dkey <- 0.0 expect_identical(na, xts:::binsearch(dkey, dvec, TRUE)) expect_identical(na, xts:::binsearch(dkey, dvec, FALSE))
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-binsearch.R
info_msg <- "test.coredata_vector" x <- xts(1, as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(target = coredata(z), current = coredata(x), info = info_msg) info_msg <- "test.coredata_named_vector" x <- xts(c(hello = 1), as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) info_msg <- "test.coredata_matrix" x <- xts(cbind(1, 9), as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) info_msg <- "test.coredata_named_matrix" x <- xts(cbind(hello = 1, world = 9), as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) info_msg <- "test.coredata_data.frame" x <- xts(data.frame(hello = 1, world = 9), as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) info_msg <- "test.coredata_ts" x <- xts(ts(1), as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) # empty objects info_msg <- "test.coredata_empty" x <- xts(, as.Date("2018-03-02")) z <- as.zoo(x) expect_identical(coredata(z), coredata(x), info = info_msg) info_msg <- "test.coredata_empty_dim" x <- xts(cbind(1, 9), as.Date("2018-03-02")) z <- as.zoo(x) x0 <- x[0,] z0 <- z[0,] expect_identical(coredata(z0), coredata(x0), info = info_msg) info_msg <- "test.coredata_empty_dim_dimnames" x <- xts(cbind(hello = 1, world = 9), as.Date("2018-03-02")) z <- as.zoo(x) x0 <- x[0,] z0 <- z[0,] expect_identical(coredata(z0), coredata(x0), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-coredata.R
data(sample_matrix) sample.data.frame <- data.frame(sample_matrix[1:15,]) sample.xts <- as.xts(sample.data.frame) info_msg <- "test.convert_data.frame_to_xts" expect_identical(sample.xts, as.xts(sample.data.frame), info_msg) info_msg <- "test.convert_data.frame_to_xts_j1" expect_identical(sample.xts[,1], as.xts(sample.data.frame)[,1], info_msg) info_msg <- "test.convert_data.frame_to_xts_i1" expect_identical(sample.xts[1,], as.xts(sample.data.frame)[1,], info_msg) info_msg <- "test.convert_data.frame_to_xts_i1j1" expect_identical(sample.xts[1,1], as.xts(sample.data.frame)[1,1], info_msg) info_msg <- "test.data.frame_reclass" expect_identical(sample.data.frame, reclass(try.xts(sample.data.frame)), info_msg) info_msg <- "test.data.frame_reclass_subset_reclass_j1" expect_identical(sample.data.frame[,1], reclass(try.xts(sample.data.frame))[,1], info_msg) # subsetting to 1 col converts to simple numeric - can't successfully handle info_msg <- "test.data.frame_reclass_subset_as.xts_j1" expect_identical(sample.data.frame[,1,drop=FALSE], reclass(try.xts(sample.data.frame)[,1]), info_msg) info_msg <- "test.data.frame_reclass_subset_data.frame_j1" # subsetting results in a vector, so can't be converted to xts expect_error(try.xts(sample.data.frame[,1]), info = info_msg) # check for as.xts.data.frame when order.by is specified info_msg <- "test.convert_data.frame_to_xts_order.by_POSIXlt" orderby = as.POSIXlt(rownames(sample.data.frame)) x <- as.xts(sample.data.frame, order.by = orderby) # tz = "" by default for as.POSIXlt.POSIXct y <- xts(coredata(sample.xts), as.POSIXlt(index(sample.xts))) expect_identical(y, x, info_msg) info_msg <- "test.convert_data.frame_to_xts_order.by_POSIXct" orderby = as.POSIXct(rownames(sample.data.frame)) x <- as.xts(sample.data.frame, order.by = orderby) expect_identical(sample.xts, x, info_msg) info_msg <- "test.convert_data.frame_to_xts_order.by_Date" # tz = "UTC" by default for as.Date.POSIXct (y), but # tz = "" by default for as.Date.character (orderby) orderby = as.Date(rownames(sample.data.frame)) x <- as.xts(sample.data.frame, order.by = orderby) y <- xts(coredata(sample.xts), as.Date(index(sample.xts), tz = "")) expect_identical(y, x, info_msg) ### data.frame with Date/POSIXct column df_date_col <- data.frame(Date = as.Date(rownames(sample.data.frame)), sample.data.frame, row.names = NULL) info_msg <- "convert data.frame to xts from Date column" x <- as.xts(df_date_col) y <- xts(coredata(sample.xts), as.Date(index(sample.xts), tz = "")) expect_equal(y, x, info = info_msg) info_msg <- "convert data.frame to xts from POSIXct column" dttm <- as.POSIXct(rownames(sample.data.frame), tz = "UTC") + runif(15)*10000 df_pxct_col <- data.frame(Timestamp = dttm, sample.data.frame, row.names = NULL) x <- as.xts(df_pxct_col) y <- xts(coredata(sample.xts), dttm) expect_equal(y, x, info = info_msg) info_msg <- "convert data.frame to xts errors when no rownames or column" df_no_col <- data.frame(sample.data.frame, row.names = NULL) expect_error(as.xts(df_no_col), pattern = "could not convert row names to a date-time and could not find a time-based column", info = info_msg) info_msg <- "keep column name for data.frame with one non-time-based column" x <- as.xts(df_date_col[, 1:2]) expect_identical(names(x), "Open", info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-data.frame.R
# POSIXct index info_msg <- "test.diff_integer_POSIXt" x <- .xts(1:5, 1:5 + 0.0) dx <- xts(rbind(NA_integer_, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) info_msg <- "test.diff_numeric_POSIXt" x <- .xts(1:5 + 1.0, 1:5 + 0.0) dx <- xts(rbind(NA_real_, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) info_msg <- "test.diff_logical_POSIXt" x <- .xts(1:5 > 2, 1:5 + 0.0) dx <- xts(rbind(NA, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) # Date index info_msg <- "test.diff_integer_Date" x <- xts(1:5, as.Date("2016-01-01") - 5:1) dx <- xts(rbind(NA_integer_, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) info_msg <- "test.diff_numeric_Date" x <- xts(1:5 + 1.0, as.Date("2016-01-01") - 5:1) dx <- xts(rbind(NA_real_, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) info_msg <- "test.diff_logical_Date" x <- xts(1:5 > 2, as.Date("2016-01-01") - 5:1) dx <- xts(rbind(NA, diff(coredata(x))), index(x)) expect_identical(diff(x), dx, info_msg) # Type-check failure errors info_msg <- "diff.xts() 'differences' argument must be integer" x <- .xts(1:5, 1:5) # (ignore NA introduced by coercion) expect_error(suppressWarnings(diff(x, 1L, "a")), info = info_msg) info_msg <- "diff.xts() 'lag' argument must be integer" x <- .xts(1:5, 1:5) # (ignore NA introduced by coercion) expect_error(suppressWarnings(diff(x, "a", 1L)), info = info_msg) info_msg <- "diff.xts() differences argument must be > 0" expect_error(diff(.xts(1:5, 1:5), 1L, -1L), info = info_msg) info_msg <- "diff.xts() lag argument must be > 0" expect_error(diff(.xts(1:5, 1:5), -1L, 1L), info = info_msg) info_msg <- "test.diff_logical_preserves_colnames" cnames <- c("a", "b") x <- .xts(matrix(rnorm(10) > 0, 5), 1:5, dimnames = list(NULL, cnames)) y <- diff(x) expect_identical(colnames(y), cnames, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-diff.R
### colnames(x) are not removed when 'x' and 'y' are shared and dimnames(y) <- NULL orig_names <- c("a", "b") x <- .xts(cbind(1:2, 1:2), 1:2, dimnames = list(NULL, orig_names)) y <- x dimnames(y) <- NULL expect_null(colnames(y), info = "dimnames(y) <- NULL removes dimnames from y") expect_identical(orig_names, colnames(x), info = "dimnames(y) <- NULL does not remove dimnames from x") ### colnames(x) are not changed when 'x' and 'y' are shared and dimnames(y) <- foo new_names <- c("c", "d") x <- .xts(cbind(1:2, 1:2), 1:2, dimnames = list(NULL, orig_names)) y <- x dimnames(y) <- list(NULL, new_names) expect_identical(new_names, colnames(y), info = "dimnames(y) <- list(NULL, new_names) set correctly on y") expect_identical(orig_names, colnames(x), info = "dimnames(y) <- list(NULL, new_names) does not change dimnames on x") new_names[1] <- "e" expect_identical(c("c", "d"), colnames(y), info = "colnames(y) not changed when new_names is changed")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-dimnames.R
# index crosses the unix epoch info_msg <- "test.double_index_cross_epoch" x <- .xts(1:22, 1.0*(-10:11), tzone="UTC") ep <- endpoints(x, "seconds", 2) expect_identical(ep, 0:11*2L, info_msg) info_msg <- "test.integer_index_cross_epoch" x <- .xts(1:22, -10:11, tzone="UTC") ep <- endpoints(x, "seconds", 2) expect_identical(ep, 0:11*2L, info_msg) #{{{daily data data(sample_matrix) xDailyDblIdx <- as.xts(sample_matrix, dateFormat="Date") xDailyIntIdx <- xDailyDblIdx storage.mode(.index(xDailyIntIdx)) <- "integer" info_msg <- "test.days_double_index" ep <- endpoints(xDailyDblIdx, "days", 7) expect_identical(ep, c(0L, 1:26*7L-3L, nrow(xDailyDblIdx)), info_msg) info_msg <- "test.days_integer_index" ep <- endpoints(xDailyIntIdx, "days", 7) expect_identical(ep, c(0L, 1:26*7L-3L, nrow(xDailyIntIdx)), info_msg) info_msg <- "test.weeks_double_index" ep <- endpoints(xDailyDblIdx, "weeks", 1) expect_identical(ep, c(0L, 1:25*7L-1L, nrow(xDailyDblIdx)), info_msg) info_msg <- "test.weeks_integer_index" ep <- endpoints(xDailyIntIdx, "weeks", 1) expect_identical(ep, c(0L, 1:25*7L-1L, nrow(xDailyIntIdx)), info_msg) info_msg <- "test.months_double_index" ep <- endpoints(xDailyDblIdx, "months", 1) expect_identical(ep, c(0L, 30L, 58L, 89L, 119L, 150L, 180L), info_msg) info_msg <- "test.months_integer_index" ep <- endpoints(xDailyIntIdx, "months", 1) expect_identical(ep, c(0L, 30L, 58L, 89L, 119L, 150L, 180L), info_msg) info_msg <- "test.quarters_double_index" ep <- endpoints(xDailyDblIdx, "quarters", 1) expect_identical(ep, c(0L, 89L, 180L), info_msg) info_msg <- "test.quarters_integer_index" ep <- endpoints(xDailyIntIdx, "quarters", 1) expect_identical(ep, c(0L, 89L, 180L), info_msg) info_msg <- "test.years_double_index" d <- seq(as.Date("1970-01-01"), by="1 day", length.out=365*5) x <- xts(seq_along(d), d) ep <- endpoints(x, "years", 1) expect_identical(ep, c(0L, 365L, 730L, 1096L, 1461L, 1825L), info_msg) info_msg <- "test.years_integer_index" d <- seq(as.Date("1970-01-01"), by="1 day", length.out=365*5) x <- xts(seq_along(d), d) storage.mode(.index(x)) <- "integer" ep <- endpoints(x, "years", 1) expect_identical(ep, c(0L, 365L, 730L, 1096L, 1461L, 1825L), info_msg) #}}} #{{{second data n <- 86400L %/% 30L * 365L * 2L xSecIntIdx <- .xts(1L:n, seq(.POSIXct(0, tz="UTC"), by="30 sec", length.out=n), tzone="UTC") xSecDblIdx <- xSecIntIdx storage.mode(.index(xSecDblIdx)) <- "double" info_msg <- "test.seconds_double_index" ep <- endpoints(xSecDblIdx, "seconds", 3600) expect_identical(ep, seq(0L, nrow(xSecDblIdx), 120L), info_msg) info_msg <- "test.seconds_integer_index" ep <- endpoints(xSecIntIdx, "seconds", 3600) expect_identical(ep, seq(0L, nrow(xSecIntIdx), 120L), info_msg) info_msg <- "test.seconds_secs" x <- .xts(1:10, 1:10/6) ep1 <- endpoints(x, "seconds") ep2 <- endpoints(x, "secs") expect_identical(ep1, ep2, info_msg) info_msg <- "test.minutes_double_index" ep <- endpoints(xSecDblIdx, "minutes", 60) expect_identical(ep, seq(0L, nrow(xSecDblIdx), 120L), info_msg) info_msg <- "test.minutes_integer_index" ep <- endpoints(xSecIntIdx, "minutes", 60) expect_identical(ep, seq(0L, nrow(xSecIntIdx), 120L), info_msg) info_msg <- "test.minutes_mins" x <- .xts(1:10, 1:10*10) ep1 <- endpoints(x, "minutes") ep2 <- endpoints(x, "mins") expect_identical(ep1, ep2, info_msg) info_msg <- "test.hours_double_index" ep <- endpoints(xSecDblIdx, "hours", 1) expect_identical(ep, seq(0L, nrow(xSecDblIdx), 120L), info_msg) info_msg <- "test.hours_integer_index" ep <- endpoints(xSecIntIdx, "hours", 1) expect_identical(ep, seq(0L, nrow(xSecIntIdx), 120L), info_msg) info_msg <- "test.days_double_index" ep <- endpoints(xSecDblIdx, "days", 1) expect_identical(ep, seq(0L, by=2880L, length.out=length(ep)), info_msg) info_msg <- "test.days_integer_index" ep <- endpoints(xSecIntIdx, "days", 1) expect_identical(ep, seq(0L, by=2880L, length.out=length(ep)), info_msg) info_msg <- "test.weeks_double_index" ep <- endpoints(xSecDblIdx, "weeks", 1) ep2 <- c(0L, seq(11520L, nrow(xSecDblIdx)-1L, 20160L), nrow(xSecDblIdx)) expect_identical(ep, ep2, info_msg) info_msg <- "test.weeks_integer_index" ep <- endpoints(xSecIntIdx, "weeks", 1) ep2 <- c(0L, seq(11520L, nrow(xSecIntIdx)-1L, 20160L), nrow(xSecIntIdx)) expect_identical(ep, ep2, info_msg) info_msg <- "test.months_double_index" ep <- endpoints(xSecDblIdx, "months", 1) n <- 86400L * c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) / 30 ep2 <- as.integer(cumsum(c(0L, n, n))) expect_identical(ep, ep2, info_msg) info_msg <- "test.months_integer_index" ep <- endpoints(xSecIntIdx, "months", 1) n <- 86400L * c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) / 30 ep2 <- as.integer(cumsum(c(0L, n, n))) expect_identical(ep, ep2, info_msg) info_msg <- "test.quarters_double_index" ep <- endpoints(xSecDblIdx, "quarters", 1) n <- 86400L * c(90, 91, 92, 92) / 30 ep2 <- as.integer(cumsum(c(0L, n, n))) expect_identical(ep, ep2, info_msg) info_msg <- "test.quarters_integer_index" ep <- endpoints(xSecIntIdx, "quarters", 1) n <- 86400L * c(90, 91, 92, 92) / 30 ep2 <- as.integer(cumsum(c(0L, n, n))) expect_identical(ep, ep2, info_msg) info_msg <- "test.years_double_index" ep <- endpoints(xSecDblIdx, "years", 1) expect_identical(ep, c(0L, 1051200L, 2102400L), info_msg) info_msg <- "test.years_integer_index" ep <- endpoints(xSecIntIdx, "years", 1) expect_identical(ep, c(0L, 1051200L, 2102400L), info_msg) #}}} # sparse endpoints could be a problem with POSIXlt elements (#169) # TODO: sparse intraday endpoints info_msg <- "test.sparse_years" x <- xts(2:6, as.Date(sprintf("199%d-06-01", 2:6))) ep <- endpoints(x, "years") expect_identical(ep, 0:5, info_msg) info_msg <- "test.sparse_quarters" x <- xts(2:6, as.Date(sprintf("199%d-06-01", 2:6))) ep <- endpoints(x, "quarters") expect_identical(ep, 0:5, info_msg) info_msg <- "test.sparse_months" x <- xts(2:6, as.Date(sprintf("199%d-06-01", 2:6))) ep <- endpoints(x, "months") expect_identical(ep, 0:5, info_msg) info_msg <- "test.sparse_weeks" x <- xts(2:6, as.Date(sprintf("199%d-06-01", 2:6))) ep <- endpoints(x, "weeks") expect_identical(ep, 0:5, info_msg) info_msg <- "test.sparse_days" x <- xts(2:6, as.Date(sprintf("199%d-06-01", 2:6))) ep <- endpoints(x, "days") expect_identical(ep, 0:5, info_msg) # sub-second resolution on Windows info_msg <- "test.sub_second_resolution" x <- .xts(1:6, .POSIXct(0:5 / 10 + 0.01)) ep <- endpoints(x, "ms", 250) expect_identical(ep, c(0L, 3L, 5L, 6L), info_msg) # precision issues info_msg <- "test.sub_second_resolution_exact" x <- .xts(1:6, .POSIXct(0:5 / 10)) ep <- endpoints(x, "ms", 250) expect_identical(ep, c(0L, 3L, 5L, 6L), info_msg) info_msg <- "test.sub_second_resolution_representation" x <- .xts(1:10, .POSIXct(1.5e9 + 0:9 / 10)) ep <- endpoints(x, "ms", 200) expect_identical(ep, seq(0L, 10L, 2L), info_msg) # on = "quarters", k > 1 info_msg <- "test.multiple_quarters" x <- xts(1:48, as.yearmon("2015-01-01") + 0:47 / 12) expect_identical(endpoints(x, "quarters", 1), seq(0L, 48L, 3L), info_msg) expect_identical(endpoints(x, "quarters", 2), seq(0L, 48L, 6L), info_msg) expect_identical(endpoints(x, "quarters", 3), c(seq(0L, 48L, 9L), 48L), info_msg) expect_identical(endpoints(x, "quarters", 4), seq(0L, 48L,12L), info_msg) expect_identical(endpoints(x, "quarters", 5), c(seq(0L, 48L,15L), 48L), info_msg) expect_identical(endpoints(x, "quarters", 6), c(seq(0L, 48L,18L), 48L), info_msg) # end(x) always in endpoints(x) result info_msg <- "test.last_obs_always_in_output" N <- 341*12 xx <- xts(rnorm(N), seq(Sys.Date(), by = "day", length.out = N)) ep <- endpoints(xx, on = "quarters", k = 2) # OK expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "quarters, k=2")) ep <- endpoints(xx, on = "quarters", k = 3) # NOPE expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "quarters, k=3")) ep <- endpoints(xx, on = "quarters", k = 4) # NOPE expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "quarters, k=4")) ep <- endpoints(xx, on = "quarters", k = 5) # NOPE expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "quarters, k=5")) ep <- endpoints(xx, on = "months", k = 2) # NOPE expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "months, k=2")) ep <- endpoints(xx, on = "months", k = 3) # OK expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "months, k=3")) ep <- endpoints(xx, on = "months", k = 4) # NOPE expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "months, k=4")) # For the "weeks" case works fine ep <- endpoints(xx, on = "weeks", k = 2) # OK expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "weeks, k=2")) ep <- endpoints(xx, on = "weeks", k = 3) # OK expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "weeks, k=3")) ep <- endpoints(xx, on = "weeks", k = 4) # OK expect_identical(end(xx), end(xx[ep,]), paste(info_msg, "weeks, k=4")) info_msg <- "test.k_less_than_1_errors" x <- xDailyIntIdx expect_error(endpoints(x, on = "years", k = 0), info = info_msg) expect_error(endpoints(x, on = "years", k = -1), info = info_msg) expect_error(endpoints(x, on = "quarters", k = 0), info = info_msg) expect_error(endpoints(x, on = "quarters", k = -1), info = info_msg) expect_error(endpoints(x, on = "months", k = 0), info = info_msg) expect_error(endpoints(x, on = "months", k = -1), info = info_msg) expect_error(endpoints(x, on = "weeks", k = 0), info = info_msg) expect_error(endpoints(x, on = "weeks", k = -1), info = info_msg) expect_error(endpoints(x, on = "days", k = 0), info = info_msg) expect_error(endpoints(x, on = "days", k = -1), info = info_msg) x <- xSecIntIdx expect_error(endpoints(x, on = "hours", k = 0), info = info_msg) expect_error(endpoints(x, on = "hours", k = -1), info = info_msg) expect_error(endpoints(x, on = "minutes", k = 0), info = info_msg) expect_error(endpoints(x, on = "minutes", k = -1), info = info_msg) expect_error(endpoints(x, on = "seconds", k = 0), info = info_msg) expect_error(endpoints(x, on = "seconds", k = -1), info = info_msg) x <- .xts(1:10, sort(1 + runif(10))) expect_error(endpoints(x, on = "ms", k = 0), info = info_msg) expect_error(endpoints(x, on = "ms", k = -1), info = info_msg) expect_error(endpoints(x, on = "us", k = 0), info = info_msg) expect_error(endpoints(x, on = "us", k = -1), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-endpoints.R
dates <- c("2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04") d1 <- data.frame(x = seq_along(dates), row.names = dates) d2 <- data.frame(d1, y = rev(seq_along(dates))) ### basic functionality on data.frame info_msg <- "test.first_xtsible_data.frame_pos_n" expect_identical(first(d1, 1), head(d1, 1), info = info_msg) expect_identical(first(d2, 1), head(d2, 1), info = info_msg) expect_identical(first(d1, "1 day"), head(d1, 1), info = info_msg) expect_identical(first(d2, "1 day"), head(d2, 1), info = info_msg) info_msg <- "test.first_xtsible_data.frame_neg_n" expect_identical(first(d1, -1), tail(d1, -1), info = info_msg) expect_identical(first(d2, -1), tail(d2, -1), info = info_msg) expect_identical(first(d1, "-1 day"), tail(d1, -1), info = info_msg) expect_identical(first(d2, "-1 day"), tail(d2, -1), info = info_msg) info_msg <- "test.first_xtsible_data.frame_zero_n" expect_identical(first(d1, 0), head(d1, 0), info = info_msg) expect_identical(first(d2, 0), head(d2, 0), info = info_msg) expect_identical(first(d1, "0 day"), head(d1, 0), info = info_msg) expect_identical(first(d2, "0 day"), head(d2, 0), info = info_msg) info_msg <- "test.last_xtsible_data.frame_pos_n" expect_identical(last(d1, 1), tail(d1, 1), info = info_msg) expect_identical(last(d2, 1), tail(d2, 1), info = info_msg) expect_identical(last(d1, "1 day"), tail(d1, 1), info = info_msg) expect_identical(last(d2, "1 day"), tail(d2, 1), info = info_msg) info_msg <- "test.last_xtsible_data.frame_neg_n" expect_identical(last(d1, -1), head(d1, -1), info = info_msg) expect_identical(last(d2, -1), head(d2, -1), info = info_msg) expect_identical(last(d1, "-1 day"), head(d1, -1), info = info_msg) expect_identical(last(d2, "-1 day"), head(d2, -1), info = info_msg) info_msg <- "test.last_xtsible_data.frame_zero_n" expect_identical(last(d1, 0), head(d1, 0), info = info_msg) expect_identical(last(d2, 0), head(d2, 0), info = info_msg) expect_identical(last(d1, "0 day"), head(d1, 0), info = info_msg) expect_identical(last(d2, "0 day"), head(d2, 0), info = info_msg) ### non-xtsible data.frames d1 <- data.frame(x = seq_along(dates), row.names = dates) d2 <- data.frame(d1, y = rev(seq_along(dates))) rownames(d1) <- rownames(d2) <- NULL info_msg <- "test.first_nonxtsible_data.frame_pos_n" expect_identical(first(d1, 1), head(d1, 1), info = info_msg) expect_identical(first(d2, 1), head(d2, 1), info = info_msg) info_msg <- "test.first_nonxtsible_data.frame_neg_n" rownames(d1) <- rownames(d2) <- NULL expect_identical(first(d1, -1), tail(d1, -1), info = info_msg) expect_identical(first(d2, -1), tail(d2, -1), info = info_msg) info_msg <- "test.first_nonxtsible_data.frame_zero_n" rownames(d1) <- rownames(d2) <- NULL expect_identical(first(d1, 0), tail(d1, 0), info = info_msg) expect_identical(first(d2, 0), tail(d2, 0), info = info_msg) info_msg <- "test.last_nonxtsible_data.frame_pos_n" rownames(d1) <- rownames(d2) <- NULL expect_identical(last(d1, 1), tail(d1, 1), info = info_msg) expect_identical(last(d2, 1), tail(d2, 1), info = info_msg) info_msg <- "test.last_nonxtsible_data.frame_neg_n" rownames(d1) <- rownames(d2) <- NULL expect_identical(last(d1, -1), head(d1, -1), info = info_msg) expect_identical(last(d2, -1), head(d2, -1), info = info_msg) info_msg <- "test.last_nonxtsible_data.frame_zero_n" rownames(d1) <- rownames(d2) <- NULL expect_identical(last(d1, 0), head(d1, 0), info = info_msg) expect_identical(last(d2, 0), head(d2, 0), info = info_msg) ### basic functionality on matrix d1 <- data.frame(x = seq_along(dates), row.names = dates) d2 <- data.frame(d1, y = rev(seq_along(dates))) m1 <- as.matrix(d1) m2 <- as.matrix(d2) info_msg <- "test.first_xtsible_matrix_pos_n" expect_identical(first(m1, 1), head(m1, 1), info = info_msg) expect_identical(first(m2, 1), head(m2, 1), info = info_msg) expect_identical(first(m1, "1 day"), head(m1, 1), info = info_msg) expect_identical(first(m2, "1 day"), head(m2, 1), info = info_msg) info_msg <- "test.first_xtsible_matrix_neg_n" expect_identical(first(m1, -1), tail(m1, -1, keepnums = FALSE), info = info_msg) expect_identical(first(m2, -1), tail(m2, -1, keepnums = FALSE), info = info_msg) expect_identical(first(m1, "-1 day"), tail(m1, -1, keepnums = FALSE), info = info_msg) expect_identical(first(m2, "-1 day"), tail(m2, -1, keepnums = FALSE), info = info_msg) info_msg <- "test.first_xtsible_matrix_zero_n" expect_identical(first(m1, 0), tail(m1, 0, keepnums = FALSE), info = info_msg) expect_identical(first(m2, 0), tail(m2, 0, keepnums = FALSE), info = info_msg) expect_identical(first(m1, "0 day"), tail(m1, 0, keepnums = FALSE), info = info_msg) expect_identical(first(m2, "0 day"), tail(m2, 0, keepnums = FALSE), info = info_msg) info_msg <- "test.last_xtsible_matrix_pos_n" expect_identical(last(m1, 1), tail(m1, 1, keepnums = FALSE), info = info_msg) expect_identical(last(m2, 1), tail(m2, 1, keepnums = FALSE), info = info_msg) expect_identical(last(m1, "1 day"), tail(m1, 1, keepnums = FALSE), info = info_msg) expect_identical(last(m2, "1 day"), tail(m2, 1, keepnums = FALSE), info = info_msg) info_msg <- "test.last_xtsible_matrix_neg_n" expect_identical(last(m1, -1), head(m1, -1), info = info_msg) expect_identical(last(m2, -1), head(m2, -1), info = info_msg) info_msg <- "test.last_xtsible_matrix_zero_n" expect_identical(last(m1, 0), head(m1, 0), info = info_msg) expect_identical(last(m2, 0), head(m2, 0), info = info_msg) info_msg <- "test.first_nonxtsible_matrix_pos_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(first(m1, 1), head(m1, 1), info = info_msg) expect_identical(first(m2, 1), head(m2, 1), info = info_msg) info_msg <- "test.first_nonxtsible_matrix_neg_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(first(m1, -1), tail(m1, -1, keepnums = FALSE), info = info_msg) expect_identical(first(m2, -1), tail(m2, -1, keepnums = FALSE), info = info_msg) info_msg <- "test.first_nonxtsible_matrix_zero_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(first(m1, 0), tail(m1, 0, keepnums = FALSE), info = info_msg) expect_identical(first(m2, 0), tail(m2, 0, keepnums = FALSE), info = info_msg) info_msg <- "test.last_nonxtsible_matrix_pos_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(last(m1, 1), tail(m1, 1, keepnums = FALSE), info = info_msg) expect_identical(last(m2, 1), tail(m2, 1, keepnums = FALSE), info = info_msg) info_msg <- "test.last_nonxtsible_matrix_neg_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(last(m1, -1), head(m1, -1), info = info_msg) expect_identical(last(m2, -1), head(m2, -1), info = info_msg) info_msg <- "test.last_nonxtsible_matrix_zero_n" rownames(m1) <- rownames(m2) <- NULL expect_identical(last(m1, 0), head(m1, 0), info = info_msg) expect_identical(last(m2, 0), head(m2, 0), info = info_msg) ### basic functionality on vector d1 <- data.frame(x = seq_along(dates), row.names = dates) d2 <- data.frame(d1, y = rev(seq_along(dates))) info_msg <- "test.first_xtsible_vector" v1 <- setNames(d1$x, rownames(d1)) expect_identical(first(v1, 1), head(v1, 1), info = info_msg) expect_identical(first(v1,-1), tail(v1,-1), info = info_msg) expect_identical(first(v1, "1 day"), head(v1, 1), info = info_msg) expect_identical(first(v1,"-1 day"), tail(v1,-1), info = info_msg) expect_identical(first(v1, "2 days"), head(v1, 2), info = info_msg) expect_identical(first(v1,"-2 days"), tail(v1,-2), info = info_msg) d <- .Date(3) + 1:21 expect_identical(first(d, "1 week"), head(d, 7), info = info_msg) expect_identical(first(d,"-1 week"), tail(d,-7), info = info_msg) expect_identical(first(d, "2 weeks"), head(d, 14), info = info_msg) expect_identical(first(d,"-2 weeks"), tail(d,-14), info = info_msg) info_msg <- "test.last_xtsible_vector" v1 <- setNames(d1$x, rownames(d1)) expect_identical(last(v1, 1), tail(v1, 1), info = info_msg) expect_identical(last(v1,-1), head(v1,-1), info = info_msg) expect_identical(last(v1, "1 day"), tail(v1, 1), info = info_msg) expect_identical(last(v1,"-1 day"), head(v1,-1), info = info_msg) d <- .Date(3) + 1:21 expect_identical(last(d, "1 week"), tail(d, 7), info = info_msg) expect_identical(last(d,"-1 week"), head(d,-7), info = info_msg) expect_identical(last(d, "2 weeks"), tail(d, 14), info = info_msg) expect_identical(last(d,"-2 weeks"), head(d,-14), info = info_msg) info_msg <- "test.first_nonxtsible_vector" v1 <- d1$x expect_identical(first(v1, 1), head(v1, 1), info = info_msg) expect_identical(first(v1,-1), tail(v1,-1), info = info_msg) expect_identical(first(v1,0), tail(v1,0), info = info_msg) info_msg <- "test.last_nonxtsible_vector" v1 <- d1$x expect_identical(last(v1, 1), tail(v1, 1), info = info_msg) expect_identical(last(v1,-1), head(v1,-1), info = info_msg) expect_identical(last(v1,0), head(v1,0), info = info_msg) ### zero-length vectors info_msg <- "test.zero_length_vector" types <- c("logical", "integer", "numeric", "complex", "character", "raw") for (type in types) { v <- vector(type, 0) expect_identical(first(v, 1), v, info = paste(info_msg, type, "- first, n = 1")) expect_identical( last(v, 1), v, info = paste(info_msg, type, "- last, n = 1")) # negative 'n' expect_identical(first(v, -1), v, info = paste(info_msg, type, "- first, n = -1")) expect_identical( last(v, -1), v, info = paste(info_msg, type, "- last, n = -1")) #zero 'n' expect_identical(first(v, 0), v, info = paste(info_msg, type, "- first, n = 0")) expect_identical( last(v, 0), v, info = paste(info_msg, type, "- last, n = 0")) } ### zero-row matrix info_msg <- "test.zero_row_matrix" types <- c("logical", "integer", "numeric", "complex", "character", "raw") for (type in types) { m <- matrix(vector(type, 0), 0) expect_identical(first(m, 1), m, info = paste(info_msg, type, "- first, n = 1")) expect_identical( last(m, 1), m, info = paste(info_msg, type, "- last, n = 1")) # negative 'n' expect_identical(first(m, -1), m, info = paste(info_msg, type, "- first, n = -1")) expect_identical( last(m, -1), m, info = paste(info_msg, type, "- last, n = -1")) #zero 'n' expect_identical(first(m, 0), m, info = paste(info_msg, type, "- first, n = 0")) expect_identical( last(m, 0), m, info = paste(info_msg, type, "- last, n = 0")) } ### tests for zoo z1 <- zoo(seq_along(dates), as.Date(dates)) z2 <- merge(x = z1, y = rev(seq_along(dates))) info_msg <- "test.first_zoo_pos_n" expect_identical(first(z1, 1), head(z1, 1), info = info_msg) expect_identical(first(z2, 1), head(z2, 1), info = info_msg) expect_identical(first(z1, "1 day"), head(z1, 1), info = info_msg) expect_identical(first(z2, "1 day"), head(z2, 1), info = info_msg) info_msg <- "test.first_zoo_neg_n" expect_identical(first(z1, -1), tail(z1, -1), info = info_msg) expect_identical(first(z2, -1), tail(z2, -1), info = info_msg) expect_identical(first(z1, "-1 day"), tail(z1, -1), info = info_msg) expect_identical(first(z2, "-1 day"), tail(z2, -1), info = info_msg) info_msg <- "test.last_zoo_pos_n" expect_identical(last(z1, 1), tail(z1, 1), info = info_msg) expect_identical(last(z2, 1), tail(z2, 1), info = info_msg) expect_identical(last(z1, "1 day"), tail(z1, 1), info = info_msg) expect_identical(last(z2, "1 day"), tail(z2, 1), info = info_msg) info_msg <- "test.last_zoo_neg_n" expect_identical(last(z1, -1), head(z1, -1), info = info_msg) expect_identical(last(z2, -1), head(z2, -1), info = info_msg) expect_identical(last(z1, "-1 day"), head(z1, -1), info = info_msg) expect_identical(last(z2, "-1 day"), head(z2, -1), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-first-last.R
info_msg <- "test.get_index_does_not_error_if_index_has_no_attributes" x <- .xts(1:3, 1:3, tzone = "UTC") ix <- index(x) ix <- ix + 3 attr(x, "index") <- 4:6 # get index (test will fail if it errors) expect_warning(index(x), info = info_msg) info_msg <- "test.set_.index_copies_index_attributes" x <- .xts(1:3, 1:3, tzone = "UTC") ix <- index(x) ix <- ix + 3 .index(x) <- 4:6 expect_equal(index(x), ix, info = info_msg) info_msg <- "test.set_index_copies_index_attributes" x <- .xts(1:3, 1:3, tzone = "UTC") ix <- index(x) ix <- ix + 3 index(x) <- .POSIXct(4:6, "UTC") expect_equal(index(x), ix, info = info_msg) # x index must be numeric, because index<-.xts coerces RHS to numeric info_msg <- "test.set_index_restores_tzone_attribute" x <- .xts(1:3, 1:3+0, tzone = "") y <- x # Ops.POSIXt drops tzone attribute when tzone = "" index(y) <- index(y) + 0 expect_identical(x, y, info = info_msg) info_msg <- "test.get_index_zero_length_Date_returns_correct_index_type" xd <- xts(1, .Date(1)) zd <- as.zoo(xd) xd_index <- index(xd[0,]) expect_true(length(xd_index) == 0, info = paste(info_msg, "- length(index) == 0")) expect_equal(index(xd[0,]), index(zd[0,]), info = info_msg) expect_equal(index(xd[0,]), .Date(numeric()), info = info_msg) info_msg <- "test.get_index_zero_length_POSIXct_returns_correct_index_type" xp <- xts(1, .POSIXct(1), tzone = "UTC") zp <- as.zoo(xp) xp_index <- index(xp[0,]) zp_index <- index(zp[0,]) zl_index <- .POSIXct(numeric(), tz = "UTC") expect_true(length(xp_index) == 0, info = paste(info_msg, "- length(index) == 0")) expect_equal(tzone(xp_index), tzone(zp_index), info = info_msg) expect_inherits(xp_index, c("POSIXct", "POSIXt"), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-index.R
have_tseries <- suppressPackageStartupMessages({ # tseries imports quantmod. Silence this message when quantmod is loaded: # # Registered S3 method overwritten by 'quantmod': # method from # as.zoo.data.frame zoo # # So I don't get confused (again) about why xts' tests load quantmod requireNamespace("tseries", quietly = TRUE) }) if (have_tseries) { library(xts) data(sample_matrix) sample.irts <- tseries::irts(as.POSIXct(rownames(sample_matrix)),sample_matrix) sample.irts.xts <- as.xts(sample.irts) info_msg <- "test.convert_irts_to_xts <- function()" expect_identical(sample.irts.xts,as.xts(sample.irts), info = info_msg) info_msg <- "test.convert_irts_to_xts_j1" expect_identical(sample.irts.xts[,1],as.xts(sample.irts)[,1], info = info_msg) info_msg <- "test.convert_irts_to_xts_i1" expect_identical(sample.irts.xts[1,],as.xts(sample.irts)[1,], info = info_msg) info_msg <- "test.convert_irts_to_xts_i1j1" expect_identical(sample.irts.xts[1,1],as.xts(sample.irts)[1,1], info = info_msg) } # requireNamespace
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-irts.R
# Tests for isOrdered() # Utility functions for tests {{{ check.isOrdered <- function(x, v = rep(TRUE, 4), msg = "") { xc <- paste(capture.output(dput(x)), collapse = " ") expect_identical(v[1], isOrdered(x, TRUE, TRUE), info = paste(msg, xc, v[1], "increasing, strictly")) expect_identical(v[2], isOrdered(x, TRUE, FALSE), info = paste(msg, xc, v[2], "increasing")) expect_identical(v[3], isOrdered(x, FALSE, FALSE), info = paste(msg, xc, v[3], "decreasing")) expect_identical(v[4], isOrdered(x, FALSE, TRUE), info = paste(msg, xc, v[4], "decreasing, strictly")) } # }}} TTTT <- rep(TRUE, 4) FFFF <- !TTTT TTFF <- c(TRUE, TRUE, FALSE, FALSE) FFTT <- !TTFF # Increasing {{{ info_msg <- "test.isOrdered_incr" check.isOrdered(1:3, TTFF, info_msg) check.isOrdered(-1:1, TTFF, info_msg) check.isOrdered(c(1, 2, 3), TTFF, info_msg) check.isOrdered(c(-1, 0, 1), TTFF, info_msg) ### NA, NaN, Inf # beg info_msg <- "test.isOrdered_incr_begNA" check.isOrdered(c(NA_integer_, 1L, 2L), FFFF, info_msg) check.isOrdered(c(NA_real_, 1, 2), TTFF, info_msg) check.isOrdered(c(NaN, 1, 2), TTFF, info_msg) check.isOrdered(c(Inf, 1, 2), FFFF, info_msg) check.isOrdered(c(-Inf, 1, 2), TTFF, info_msg) # mid info_msg <- "test.isOrdered_incr_midNA" check.isOrdered(c(1L, NA_integer_, 2L), FFFF, info_msg) check.isOrdered(c(1, NA_real_, 2), TTTT, info_msg) check.isOrdered(c(1, NaN, 2), TTTT, info_msg) check.isOrdered(c(1, Inf, 2), FFFF, info_msg) check.isOrdered(c(1, -Inf, 2), FFFF, info_msg) # end info_msg <- "test.isOrdered_incr_endNA" check.isOrdered(c(1L, 2L, NA_integer_), TTFF, info_msg) check.isOrdered(c(1, 2, NA_real_), TTFF, info_msg) check.isOrdered(c(1, 2, NaN), TTFF, info_msg) check.isOrdered(c(1, 2, Inf), TTFF, info_msg) check.isOrdered(c(1, 2, -Inf), FFFF, info_msg) ### # }}} # Decreasing {{{ info_msg <- "test.isOrdered_decr" check.isOrdered(1:-1, FFTT, info_msg) check.isOrdered(3:1, FFTT, info_msg) check.isOrdered(c(3, 2, 1), FFTT, info_msg) check.isOrdered(c(1, 0, -1), FFTT, info_msg) ### NA, NaN, Inf # beg info_msg <- "test.isOrdered_decr_begNA" check.isOrdered(c(NA_integer_, 2L, 1L), FFTT, info_msg) check.isOrdered(c(NA_real_, 2, 1), FFTT, info_msg) check.isOrdered(c(NaN, 2, 1), FFTT, info_msg) check.isOrdered(c(Inf, 2, 1), FFTT, info_msg) check.isOrdered(c(-Inf, 2, 1), FFFF, info_msg) # mid info_msg <- "test.isOrdered_decr_midNA" check.isOrdered(c(2L, NA_integer_, 1L), FFFF, info_msg) check.isOrdered(c(2, NA_real_, 1), TTTT, info_msg) check.isOrdered(c(2, NaN, 1), TTTT, info_msg) check.isOrdered(c(2, Inf, 1), FFFF, info_msg) check.isOrdered(c(2, -Inf, 1), FFFF, info_msg) # end info_msg <- "test.isOrdered_decr_endNA" check.isOrdered(c(2L, 1L, NA_integer_), FFFF, info_msg) check.isOrdered(c(2, 1, NA_real_), FFTT, info_msg) check.isOrdered(c(2, 1, NaN), FFTT, info_msg) check.isOrdered(c(2, 1, Inf), FFFF, info_msg) check.isOrdered(c(2, 1, -Inf), FFTT, info_msg) ### # }}}
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-isordered.R
LAG <- function(x, k=1, na.pad=TRUE) { z <- lag(as.zoo(x), -k, na.pad) dimnames(z) <- NULL as.xts(z) } ### POSIXct index info_msg <- "test.lag_integer_POSIXt" x <- .xts(1:5, 1:5 + 0.0) expect_identical(lag(x), LAG(x), info = info_msg) info_msg <- "test.lag_numeric_POSIXt" x <- .xts(1:5 + 1.0, 1:5 + 0.0) expect_identical(lag(x), LAG(x), info = info_msg) info_msg <- "test.lag_logical_POSIXt" x <- .xts(1:5 > 2, 1:5 + 0.0) expect_identical(lag(x), LAG(x), info = info_msg) ### Date index info_msg <- "test.lag_integer_Date" x <- xts(1:5, as.Date("2016-01-01") - 5:1) expect_identical(lag(x), LAG(x), info = info_msg) info_msg <- "test.lag_numeric_Date" x <- xts(1:5 + 1.0, as.Date("2016-01-01") - 5:1) expect_identical(lag(x), LAG(x), info = info_msg) info_msg <- "test.lag_logical_Date" x <- xts(1:5 > 2, as.Date("2016-01-01") - 5:1) expect_identical(lag(x), LAG(x), info = info_msg) ### Type-check failure errors info_msg <- "test.lag_k_NA" x <- .xts(1:5, 1:5) expect_error(suppressWarnings(lag(x, "a")), # NA introduced by coercion "'k' must be integer", info = info_msg) info_msg <- "test.lag_k_zero_length" x <- .xts(1:5, 1:5) expect_error(suppressWarnings(lag(x, 1L, "a")), # NA introduced by coercion "'na.pad' must be logical", info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-lag.R
data(sample_matrix) sample.matrix <- sample_matrix sample.xts <- as.xts(sample.matrix) info_msg <- "test.convert_matrix_to_xts" expect_identical(sample.xts, as.xts(sample.matrix), info = info_msg) info_msg <- "test.convert_matrix_to_xts_j1" expect_identical(sample.xts[, 1], as.xts(sample.matrix)[, 1], info = info_msg) info_msg <- "test.convert_matrix_to_xts_i1" expect_identical(sample.xts[1,], as.xts(sample.matrix)[1,], info = info_msg) info_msg <- "test.convert_matrix_to_xts_i1j1" expect_identical(sample.xts[1, 1], as.xts(sample.matrix)[1, 1], info = info_msg) info_msg <- "test.matrix_reclass" expect_identical(sample.matrix, reclass(try.xts(sample.matrix)), info = info_msg) info_msg <- "test.matrix_reclass_subset_reclass_j1" expect_identical(sample.matrix[, 1], reclass(try.xts(sample.matrix))[, 1], info = info_msg) info_msg <- "test.matrix_reclass_subset_as.xts_j1" expect_identical(sample.matrix[, 1, drop = FALSE], reclass(try.xts(sample.matrix)[, 1]), info = info_msg) expect_identical(sample.matrix[, 1], reclass(try.xts(sample.matrix))[, 1], info = info_msg) info_msg <- "test.matrix_reclass_subset_matrix_j1" expect_identical(sample.matrix[, 1, drop = FALSE], reclass(try.xts(sample.matrix[, 1, drop = FALSE])), info = info_msg) ### zero-width to matrix info_msg <- "test.zero_width_xts_to_matrix" x <- .xts(,1) xm <- as.matrix(x) zm <- as.matrix(as.zoo(x)) expect_identical(xm, zm, info = info_msg) ### dim-less xts to matrix info_msg <- "test.dimless_xts_to_matrix" ix <- structure(1:3, tclass = c("POSIXct", "POSIXt"), tzone = "") x <- structure(1:3, index = ix, class = c("xts", "zoo")) m <- matrix(1:3, 3, 1, dimnames = list(format(.POSIXct(1:3)), "x")) expect_identical(as.matrix(x), m, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-matrix.R
zero_width_xts <- xts() info_msg <- "test.merge_empty_xts_with_2_scalars" m1 <- merge(zero_width_xts, 1, 1) m2 <- merge(merge(zero_width_xts, 1), 1) expect_identical(m1, zero_width_xts) expect_identical(m2, zero_width_xts) info_msg <- "test.merge_more_than_2_zero_width_objects" m1 <- merge(zero_width_xts, zero_width_xts, zero_width_xts) expect_identical(m1, zero_width_xts) ### Tests for NA in index. Construct xts object using structure() because ### xts constructors should not allow users to create objects with NA in ### the index indexHasNA_dbl <- structure(1:5, .Dim = c(5L, 1L), index = structure(c(1, 2, 3, 4, NA), tzone = "", tclass = c("POSIXct", "POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo")) indexHasNA_int <- structure(1:5, .Dim = c(5L, 1L), index = structure(c(1L, 2L, 3L, 4L, NA), tzone = "", tclass = c("POSIXct", "POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo")) info_msg <- "test.merge_index_contains_NA_integer" expect_error(merge(indexHasNA_int, indexHasNA_int), info = info_msg) info_msg <- "test.merge_index_contains_NA_double" expect_error(merge(indexHasNA_dbl, indexHasNA_dbl), info = info_msg) info_msg <- "test.merge_index_contains_NaN" x <- indexHasNA_dbl idx <- attr(x, "index") idx[length(idx)] <- NaN attr(x, "index") <- idx expect_error(merge(x, x), info = info_msg) info_msg <- "test.merge_index_contains_Inf" x <- indexHasNA_dbl idx <- attr(x, "index") idx[length(idx)] <- Inf attr(x, "index") <- idx expect_error(merge(x, x), info = info_msg) idx <- rev(idx) idx[1L] <- -Inf attr(x, "index") <- idx expect_error(merge(x, x), info = info_msg) ### /end Tests for NA in index ### zero-length fill argument info_msg <- "test.merge_fill_NULL" x1 <- .xts(1, 1) x2 <- .xts(2, 2) x <- merge(x1, x2, fill = NULL) out <- .xts(matrix(c(1, NA, NA, 2), 2), c(1,2)) colnames(out) <- c("x1", "x2") expect_identical(x, out, info = info_msg) info_msg <- "test.merge_fill_zero_length" x1 <- .xts(1, 1) x2 <- .xts(2, 2) x <- merge(x1, x2, fill = numeric()) out <- .xts(matrix(c(1, NA, NA, 2), 2), c(1,2)) colnames(out) <- c("x1", "x2") expect_identical(x, out, info = info_msg) info_msg <- "test.merge_with_zero_width_returns_original_type" M1 <- .xts(1:3, 1:3, dimnames = list(NULL, "m1")) types <- c("double", "integer", "logical", "character") for (type in types) { m1 <- M1 storage.mode(m1) <- type e1 <- .xts(,1:3) m2 <- merge(m1, e1) expect_identical(m1, m2, info = paste(info_msg, "- type =", type)) } info_msg <- "test.n_way_merge_on_all_types" D1 <- as.Date("2018-01-03")-2:0 M1 <- xts(1:3, D1, dimnames = list(NULL, "m")) M3 <- xts(cbind(1:3, 1:3, 1:3), D1, dimnames = list(NULL, c("m", "m.1", "m.2"))) types <- c("double", "integer", "logical", "character", "complex") for (type in types) { m1 <- M1 m3 <- M3 storage.mode(m1) <- storage.mode(m3) <- type m <- merge(m1, m1, m1) expect_identical(m, m3, info = paste(info_msg, "- type =", type)) } info_msg <- "test.shorter_colnames_for_unnamed_args" X <- .xts(rnorm(10, 10), 1:10) types <- c("double", "integer", "logical", "character", "complex") for (type in types) { x <- X storage.mode(x) <- type mx <- do.call(merge, list(x, x)) expect_true(all(nchar(colnames(mx)) < 200), info = paste(info_msg, "- type = ", type)) } info_msg <- "test.check_names_false" x <- .xts(1:3, 1:3, dimnames = list(NULL, "42")) y <- .xts(1:3, 1:3, dimnames = list(NULL, "21")) z <- merge(x, y) # leading "X" added expect_identical(colnames(z), c("X42", "X21"), info = info_msg) z <- merge(x, y, check.names = TRUE) # same expect_identical(colnames(z), c("X42", "X21"), info = info_msg) z <- merge(x, y, check.names = FALSE) # should have numeric column names expect_identical(colnames(z), c("42", "21"), info = info_msg) info_msg <- "test.merge_fills_complex_types" data. <- cbind(c(1:5*1i, NA, NA), c(NA, NA, 3:7*1i)) colnames(data.) <- c("x", "y") d21 <- data. d21[is.na(d21)] <- 21i x <- xts(1:5 * 1i, as.Date(1:5, origin = "1970-01-01")) y <- xts(3:7 * 1i, as.Date(3:7, origin = "1970-01-01")) z <- merge(x, y) expect_equivalent(coredata(z), data., info = paste(info_msg, "- default fill")) z <- merge(x, y, fill = 21i) expect_equivalent(coredata(z), d21, info = paste(info_msg, "- fill = 21i")) .index(x) <- as.integer(.index(x)) .index(y) <- as.integer(.index(y)) z <- merge(x, y) expect_equivalent(coredata(z), data., info = paste(info_msg, "- default fill, integer index")) z <- merge(x, y, fill = 21i) expect_equivalent(coredata(z), d21, info = paste(info_msg, "- fill = 21i, integer index")) info_msg <- "test.suffixes_appended" x <- xts(data.frame(x = 1), as.Date("2012-01-01")) y <- xts(data.frame(x = 2), as.Date("2012-01-01")) suffixes <- c("truex", "truey") out <- merge(x, y, suffixes = suffixes) expect_equal(paste0("x", suffixes), colnames(out), info = info_msg) info_msg <- "test.suffix_append_order" idx <- Sys.Date() - 1:10 x1 <- xts(cbind(alpha = 1:10, beta = 2:11), idx) x2 <- xts(cbind(alpha = 3:12, beta = 4:13), idx) x3 <- xts(cbind(alpha = 5:14, beta = 6:15), idx) suffixes <- LETTERS[1:3] mx <- merge(x1, x2, x3, suffixes = paste0('.', suffixes)) mz <- merge.zoo(x1, x2, x3, suffixes = suffixes) expect_equal(mx, as.xts(mz), info = info_msg) ### merging zero-width objects z1 <- structure(numeric(0), index = structure(1:10, class = "Date"), class = "zoo") x1 <- as.xts(z1) z2 <- structure(numeric(0), index = structure(5:14, class = "Date"), class = "zoo") x2 <- as.xts(z2) info_msg <- "merge.xts() on zero-width objects and all = TRUE matches merge.zoo()" z3 <- merge(z1, z2, all = TRUE) x3 <- merge(x1, x2, all = TRUE) # use expect_equivalent because xts index has tclass and tzone and zoo doesn't expect_equivalent(index(z3), index(x3), info = info_msg) info_msg <- "merge.xts() zero-width objects and all = FALSE matches merge.zoo()" z4 <- merge(z1, z2, all = FALSE) x4 <- merge(x1, x2, all = FALSE) # use expect_equivalent because xts index has tclass and tzone and zoo doesn't expect_equivalent(index(z4), index(x4), info = info_msg) info_msg <- "merge.xts() on zero-width objects and all = c(TRUE, FALSE) matches merge.zoo()" z5 <- merge(z1, z2, all = c(TRUE, FALSE)) x5 <- merge(x1, x2, all = c(TRUE, FALSE)) # use expect_equivalent because xts index has tclass and tzone and zoo doesn't expect_equivalent(index(z5), index(x5), info = info_msg) info_msg <- "merge.xts() on zero-width objects and all = c(FALSE, TRUE) matches merge.zoo()" z6 <- merge(z1, z2, all = c(FALSE, TRUE)) x6 <- merge(x1, x2, all = c(FALSE, TRUE)) # use expect_equivalent because xts index has tclass and tzone and zoo doesn't expect_equivalent(index(z6), index(x6), info = info_msg) ### merge.xts() matches merge.zoo() for various calls on zero-length objects with column names x <- xts(matrix(1:9, 3, 3), .Date(17167:17169), dimnames = list(NULL, c("a","b","c"))) z <- as.zoo(x) x0 <- xts(coredata(x), index(x)+5)[FALSE] z0 <- zoo(coredata(z), index(z)+5)[FALSE] xm1 <- merge(x, x0, all = c(TRUE, FALSE)) zm1 <- merge(z, z0, all = c(TRUE, FALSE)) expect_equivalent(coredata(xm1), coredata(zm1), info = "merge.xts(x, empty_named, all = c(TRUE, FALSE)) coredata matches merge.zoo()") expect_equivalent(index(xm1), index(zm1), info = "merge.xts(x, empty_named, all = c(TRUE, FALSE)) index matches merge.zoo()") xm2 <- merge(x0, x, all = c(FALSE, TRUE)) zm2 <- merge(z0, z, all = c(FALSE, TRUE)) expect_equivalent(coredata(xm2), coredata(zm2), info = "merge.xts(empty_named, x, all = c(FALSE, TRUE)) coredata matches merge.zoo()") expect_equivalent(index(xm2), index(zm2), info = "merge.xts(empty_named, x, all = c(FALSE, TRUE)) index matches merge.zoo()") xm3 <- merge(x, x0) zm3 <- merge(z, z0) expect_equivalent(coredata(xm3), coredata(zm3), info = "merge.xts(x, empty_named) coredata matches merge.zoo()") expect_equivalent(index(xm3), index(zm3), info = "merge.xts(x, empty_named) index matches merge.zoo()") xm4 <- merge(x0, x) zm4 <- merge(z0, z) expect_equivalent(coredata(xm4), coredata(zm4), info = "merge.xts(empty_named, x) coredata matches merge.zoo()") expect_equivalent(index(xm4), index(zm4), info = "merge.xts(empty_named, x) index matches merge.zoo()") # merge.zoo() returns an empty object in these cases, so we can't expect merge.xts() to match merge.zoo() #xm5 <- merge(x0, x0) #zm5 <- merge(z0, z0) #expect_equivalent(xm5, zm5, info = "merge.xts([empty_named 2x]) matches merge.zoo()") #xm6 <- merge(x0, x0, x0) #zm6 <- merge(z0, z0, z0) #expect_equivalent(xm6, zm6, info = "merge.xts([empty_named 3x]) matches merge.zoo()") xm5 <- merge(x0, x0) empty_with_dims_2x <- structure(integer(0), dim = c(0L, 6L), index = .index(x0), dimnames = list(NULL, c("a", "b", "c", "a.1", "b.1", "c.1")), class = c("xts", "zoo")) expect_identical(xm5, empty_with_dims_2x, info = "merge.xts([empty_xts_with_dims 2x]) has correct dims") # merge.zoo() returns an empty object in this case, so we can't expect merge.xts() to match merge.zoo() xm6 <- merge(x0, x0, x0) empty_with_dims_3x <- structure(integer(0), dim = c(0L, 9L), index = .index(x0), dimnames = list(NULL, c("a", "b", "c", "a.1", "b.1", "c.1", "a.2", "b.2", "c.2")), class = c("xts", "zoo")) storage.mode(.index(empty_with_dims_3x)) <- "integer" ## FIXME: this should be 'numeric expect_identical(xm6, empty_with_dims_3x, info = "merge.xts([empty_xts_with_dims 3x]) has correct dims") xm7 <- merge(x0, x, x0) zm7 <- merge(z0, z, z0) expect_equivalent(coredata(xm7), coredata(zm7), info = "merge.xts(empty_named, x_named, empty_named) coredata matches merge.zoo()") expect_equivalent(index(xm7), index(zm7), info = "merge.xts(empty_named, x_named, empty_named) index matches merge.zoo()") xz <- xts(integer(0), .Date(integer(0))) expect_identical(storage.mode(merge(xz, xz)), "integer", info = "merge.xts() on two empty objects should return an object with the same type") ### merging xts with plain vectors x <- xts(matrix(1:9, 3, 3), .Date(17167:17169), dimnames = list(NULL, c("a","b","c"))) z <- as.zoo(x) v <- seq_len(nrow(x)) x1 <- merge(x, v) z1 <- merge(z, v) expect_equivalent(coredata(x1), coredata(z1), info = "merge.xts(x_named, vector) coredata matches merge.zoo()") expect_equivalent(index(x1), index(z1), info = "merge.xts(x_named, vector) index matches merge.zoo()") x2 <- merge(x, x, v) z2 <- merge(z, z, v) expect_equivalent(coredata(x2), coredata(z2), info = "merge.xts(x_named_2x, vector) coredata matches merge.zoo()") expect_equivalent(index(x2), index(z2), info = "merge.xts(x_named_2x, vector) index matches merge.zoo()") x3 <- merge(x, v, x) z3 <- merge(z, v, z) expect_equivalent(coredata(x3), coredata(z3), info = "merge.xts(x_named, vector, x_named) coredata matches merge.zoo()") expect_equivalent(index(x3), index(z3), info = "merge.xts(x_named, vector, x_named) index matches merge.zoo()")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-merge.R
info_msg <- "na.fill.xts() matches na.fill.zoo() when object has 1 column and 'fill' is scalar" x <- .xts(1:20, 1:20) is.na(x) <- sample(20, 10) z <- as.zoo(x) x_out <- coredata(na.fill(x, 0)) z_out <- coredata(na.fill(z, 0)) expect_equal(z_out, x_out, info = info_msg) info_msg <- "na.fill.xts() matches na.fill.zoo() when object has 2 columns and 'fill' is scalar" x <- .xts(cbind(1:10, 1:10), 1:10) is.na(x[,1]) <- sample(10, 5) is.na(x[,2]) <- sample(10, 5) z <- as.zoo(x) x_out <- coredata(na.fill(x, 0)) z_out <- coredata(na.fill(z, 0)) # z_out has dimnames (both NULL) for some reason dimnames(z_out) <- NULL expect_equal(z_out, x_out, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-na.fill.R
xdata <- .xts(c(1, NA, 3, 4, 5, 6), c(0, 4, 10, 19, 24, 29)) xdata2 <- merge(one = xdata, two = xdata) xindex <- .xts(rep(0, 5), c(5, 10, 20, 25, 28)) types <- c("double", "integer", "character", "logical") ### na.locf.xts() on a univariate xts object info_msg <- "test.nalocf" for (type in types) { xdat <- xdata storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat) z <- na.locf(zdat) #expect_identical(x, as.xts(z)) # FALSE (attribute order differs) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_leading_NA" for (type in types) { xdat <- xdata storage.mode(xdat) <- type zdat <- as.zoo(xdat) xdat[1] <- NA zdat[1] <- NA x <- na.locf(xdat, na.rm = TRUE) z <- na.locf(zdat, na.rm = TRUE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) x <- na.locf(xdat, na.rm = FALSE) z <- na.locf(zdat, na.rm = FALSE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_fromLast" for (type in types) { xdat <- xdata storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat, fromLast = TRUE) z <- na.locf(zdat, fromLast = TRUE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_x" for (type in types) { xdat <- xdata xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) xidx <- rbind(xidx, .xts(vector(type, 1), 30)) zidx <- as.zoo(xidx) x <- na.locf(xdat, x = index(xidx)) z <- na.locf(zdat, x = index(zidx)) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_xout" for (type in types) { xdat <- xdata xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) x <- na.locf(xdat, xout = index(xidx)) z <- na.locf(zdat, xout = index(zidx)) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } ### na.locf.xts() on a multivariate xts object info_msg <- "test.nalocf_by_column" for (type in types) { xdat <- xdata2 storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat) z <- na.locf(zdat) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_leading_NA" for (type in types) { xdat <- xdata2 storage.mode(xdat) <- type zdat <- as.zoo(xdat) xdat[1] <- NA zdat[1] <- NA if (FALSE) { ### bug w/zoo causes this to fail ### zoo:::na.locf.default() does not remove the first row x <- na.locf(xdat, na.rm = TRUE) z <- na.locf(zdat, na.rm = TRUE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } x <- na.locf(xdat, na.rm = FALSE) z <- na.locf(zdat, na.rm = FALSE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_fromLast" for (type in types) { xdat <- xdata2 storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat, fromLast = TRUE) z <- na.locf(zdat, fromLast = TRUE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_x" for (type in types) { xdat <- xdata2 xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) xidx <- rbind(xidx, .xts(vector(type, 1), 30)) zidx <- as.zoo(xidx) x <- na.locf(xdat, x = index(xidx)) z <- na.locf(zdat, x = index(zidx)) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_xout" for (type in types) { xdat <- xdata2 xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) x <- na.locf(xdat, xout = index(xidx)) z <- na.locf(zdat, xout = index(zidx)) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_1NA" narow <- 1L for (type in types) { xdrow <- xdata2[narow,] xdat <- xdata2 * NA xdat[narow,] <- xdrow storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat) z <- na.locf(zdat) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_by_column_1NA_fromLast" narow <- nrow(xdata2) for (type in types) { xdrow <- xdata2[narow,] xdat <- xdata2 * NA xdat[narow,] <- xdrow storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat, fromLast = TRUE) z <- na.locf(zdat, fromLast = TRUE) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_first_column_all_NA" nacol <- 1L for (type in types) { xdat <- xdata2 xdat[,nacol] <- xdat[,nacol] * NA storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat) z <- na.locf(zdat) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.nalocf_last_column_all_NA" nacol <- NCOL(xdata2) for (type in types) { xdat <- xdata2 xdat[,nacol] <- xdat[,nacol] * NA storage.mode(xdat) <- type zdat <- as.zoo(xdat) x <- na.locf(xdat) z <- na.locf(zdat) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) }
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-na.locf.R
xdata <- .xts(c(1, NA, 3, 4, 5, 6), c(0, 4, 10, 19, 24, 29)) xindex <- .xts(rep(0, 5), c(5, 10, 20, 25, 28)) types <- c("double", "integer", "character", "logical") info_msg <- "test.naomit" for (type in types) { xdat <- xdata xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) x <- na.omit(xdat) z <- na.omit(zdat) # na.omit.xts adds "index" attribute to the "na.action" attribute attr(attr(x, "na.action"), "index") <- NULL #expect_identical(x, as.xts(z)) # FALSE (attribute order differs) expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) } info_msg <- "test.naomit_by_column" for (type in types) { xdat <- xdata xidx <- xindex storage.mode(xdat) <- storage.mode(xidx) <- type zdat <- as.zoo(xdat) zidx <- as.zoo(xidx) x <- na.omit(merge(one = xdat, two = xdat)) z <- na.omit(merge(one = zdat, two = zdat)) # na.omit.xts adds "index" attribute to the "na.action" attribute attr(attr(x, "na.action"), "index") <- NULL expect_equal(x, as.xts(z), info = paste(info_msg, "-", type)) }
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-na.omit.R
# Constants TZ <- "UTC" START_N <- 1424390400 START_T <- .POSIXct(START_N, "UTC") END_N <- 1425168000 END_T <- .POSIXct(1425168000, "UTC") ### Test basic functionality for dates (TODO: date-times) info_msg <- "test.all_dates" out <- list(first.time = START_T, last.time = END_T) y <- .parseISO8601("/", START_N, END_N, "UTC") expect_identical(y, out, info = info_msg) y <- .parseISO8601("::", START_N, END_N, "UTC") expect_identical(y, out, info = info_msg) info_msg <- "test.start_to_right_open" y <- .parseISO8601("2015-02-21/", START_N, END_N, "UTC") start_t <- as.POSIXct("2015-02-21", tz = "UTC") expect_identical(y, list(first.time = start_t, last.time = END_T), info = info_msg) info_msg <- "test.left_open_to_end" y <- .parseISO8601("/2015-02-21", START_N, END_N, "UTC") end_t <- as.POSIXct("2015-02-22", tz = "UTC") - 1e-5 expect_identical(y, list(first.time = START_T, last.time = end_t), info = info_msg) info_msg <- "test.left_open_to_end" y <- .parseISO8601("/2015-02-21", START_N, END_N, "UTC") end_t <- as.POSIXct("2015-02-22", tz = "UTC") - 1e-5 expect_identical(y, list(first.time = START_T, last.time = end_t), info = info_msg) info_msg <- "test.single_date" y <- .parseISO8601("2015-02-21", START_N, END_N, "UTC") start_t <- as.POSIXct("2015-02-21", tz = "UTC") end_t <- as.POSIXct("2015-02-22", tz = "UTC") - 1e-5 expect_identical(y, list(first.time = start_t, last.time = end_t), info = info_msg) ### Test expected failures ### These don't produce errors, but instead return values in UNKNOWN_TIME UNKNOWN_TIME <- list(first.time = NA_real_, last.time = NA_real_) info_msg <- "test.start_end_dates_do_not_exist" x <- "2014-02-30/2015-02-30" expect_warning(y <- .parseISO8601(x, START_N, END_N, "UTC"), pattern = "cannot determine first and last time") y <- suppressWarnings(.parseISO8601(x, START_N, END_N, "UTC")) expect_identical(y, UNKNOWN_TIME, info = info_msg) ### test.start_date_does_not_exist <- function() { ### DEACTIVATED("FAILS: returns everything") ### x <- "2015-02-30/2015-03-03" ### y <- .parseISO8601(x, START_N, END_N, "UTC") ### expect_identical(y, UNKNOWN_TIME, info = info_msg) ### } ### ### test.end_date_does_not_exist <- function() { ### DEACTIVATED("FAILS: returns everything") ### x <- "2015-02-25/2015-02-30" ### y <- .parseISO8601(x, START_N, END_N, "UTC") ### expect_identical(y, UNKNOWN_TIME, info = info_msg) ### } ### Fuzz tests info_msg <- "test.start_end_dates_are_garbage" x <- "0.21/8601.21" expect_warning(y <- .parseISO8601(x, START_N, END_N, "UTC"), pattern = "cannot determine first and last time") expect_identical(y, UNKNOWN_TIME, info = info_msg) info_msg <- "test.start_date_is_garbage" out <- list(first.time = START_T, last.time = as.POSIXct("2015-02-22", tz = "UTC") - 1e-5) x <- "garbage/2015-02-21" expect_warning(y <- .parseISO8601(x, START_N, END_N, "UTC"), pattern = "NAs introduced by coercion") expect_identical(y, out, info = info_msg) x <- "0.21/2015-02-21" y <- .parseISO8601(x, START_N, END_N, "UTC") expect_identical(y, out, info = info_msg) info_msg <- "test.end_date_is_garbage" out <- list(first.time = as.POSIXct("2015-02-25", tz = "UTC"), last.time = END_T) ### # ERRORS (uninformative) ### x <- "2015-02-25/garbage" ### y <- .parseISO8601(x, START_N, END_N, "UTC") ### expect_identical(y, UNKNOWN_TIME, info = info_msg) x <- "2015-02-25/8601.21" y <- .parseISO8601(x, START_N, END_N, "UTC") expect_identical(y, out, info = info_msg) info_msg <- "test.single_date_is_garbage" ### # ERRORS (uninformative) ### y <- .parseISO8601("garbage", START_N, END_N, "UTC") ### expect_identical(y, UNKNOWN_TIME, info = info_msg) expect_warning(y <- .parseISO8601("0.21", START_N, END_N, "UTC"), pattern = "cannot determine first and last time") expect_identical(y, UNKNOWN_TIME, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-parseISO8601.R
# period.apply() doesn't care what generates the INDEX, # but it does care that INDEX has the following characteristics: # 1) the first element is zero, # 2) the last element is nrow(x), # 3) there are no duplicate elements, # 4) the elements are sorted. # info_msg <- "test.duplicate_INDEX" x <- .xts(1:10, 1:10) ep <- c(0, 2, 4, 6, 8, 10) nodup <- period.apply(x, ep, sum) dup <- period.apply(x, c(ep, 10), sum) expect_identical(nodup, dup, info = info_msg) info_msg <- "test.duplicate_INDEX_vector" x <- 1:10 ep <- c(0, 2, 4, 6, 8, 10) nodup <- period.apply(x, ep, sum) dup <- period.apply(x, c(ep, 10), sum) expect_identical(nodup, dup, info = info_msg) info_msg <- "test.unsorted_INDEX" x <- .xts(1:10, 1:10) ep.s <- c(2, 4, 6, 8) ep.u <- sample(ep.s) s <- period.apply(x, c(0, ep.s, 10), sum) u <- period.apply(x, c(0, ep.u, 10), sum) expect_identical(s, u, info = info_msg) info_msg <- "test.unsorted_INDEX_vector" x <- 1:10 ep.s <- c(2, 4, 6, 8) ep.u <- sample(ep.s) s <- period.apply(x, c(0, ep.s, 10), sum) u <- period.apply(x, c(0, ep.u, 10), sum) expect_identical(s, u, info = info_msg) info_msg <- "test.INDEX_starts_with_zero" x <- .xts(1:10, 1:10) ep <- c(2, 4, 6, 8, 10) a <- period.apply(x, ep, sum) z <- period.apply(x, c(0, ep), sum) expect_identical(a, z, info = info_msg) info_msg <- "test.INDEX_starts_with_zero_vector" x <- 1:10 ep <- c(2, 4, 6, 8, 10) a <- period.apply(x, ep, sum) z <- period.apply(x, c(0, ep), sum) expect_identical(a, z, info = info_msg) info_msg <- "test.INDEX_ends_with_lengthX" x <- .xts(1:10, 1:10) ep <- c(0, 2, 4, 6, 8) a <- period.apply(x, ep, sum) z <- period.apply(x, c(ep, 10), sum) expect_identical(a, z, info = info_msg) info_msg <- "test.INDEX_ends_with_lengthX_vector" x <- 1:10 ep <- c(0, 2, 4, 6, 8) a <- period.apply(x, ep, sum) z <- period.apply(x, c(ep, 10), sum) expect_identical(a, z, info = info_msg) # check specific period.* functions data(sample_matrix) x <- as.xts(sample_matrix[,1], dateFormat = "Date") e <- endpoints(x, "months") info_msg <- "test.period.min_equals_apply.monthly" # min am <- apply.monthly(x, min) pm <- period.min(x, e) expect_equivalent(am, pm, info = info_msg) info_msg <- "test.period.max_equals_apply.monthly" # max am <- apply.monthly(x, max) pm <- period.max(x, e) expect_equivalent(am, pm, info = info_msg) info_msg <- "test.period.sum_equals_apply.monthly" # sum am <- apply.monthly(x, sum) pm <- period.sum(x, e) expect_equivalent(am, pm, info = info_msg) info_msg <- "test.period.prod_equals_apply.monthly" # prod am <- apply.monthly(x, prod) pm <- period.prod(x, e) expect_equivalent(am, pm, info = info_msg) # test that non-integer INDEX is converted to integer info_msg <- "test.period.min_converts_index_to_integer" storage.mode(e) <- "numeric" pm <- period.min(x, e) info_msg <- "test.period.max_converts_index_to_integer" storage.mode(e) <- "numeric" pm <- period.max(x, e) info_msg <- "test.period.sum_converts_index_to_integer" storage.mode(e) <- "numeric" pm <- period.sum(x, e) info_msg <- "test.period.prod_converts_index_to_integer" storage.mode(e) <- "numeric" pm <- period.prod(x, e) # test conversion from intraday to daily or lower frequency info_msg <- "test.intraday_to_daily" set.seed(21) i <- as.POSIXct("2013-02-05 01:01", tz = "America/Chicago") x <- xts(rnorm(10000), i - 10000:1 * 60) d <- to.daily(x) dateseq <- seq(as.Date("2013-01-29"), as.Date("2013-02-05"), "day") expect_equivalent(index(d), dateseq, info = info_msg) # message for FUN = mean expect_message(period.apply(x, e, mean), pattern = "period\\.apply\\(..., FUN = mean\\)") expect_message(apply.daily(x, mean), pattern = "apply\\.daily\\(..., FUN = mean\\)") expect_message(apply.monthly(x, mean), pattern = "apply\\.monthly\\(..., FUN = mean\\)") expect_message(apply.quarterly(x, mean), pattern = "apply\\.quarterly\\(..., FUN = mean\\)") expect_message(apply.yearly(x, mean), pattern = "apply\\.yearly\\(..., FUN = mean\\)")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-period.apply.R
P <- structure( list(difftime = structure(0, units = "secs", class = "difftime"), frequency = 0, start = structure(.POSIXct(1, "UTC"), tclass = c("POSIXct", "POSIXt")), end = structure(.POSIXct(1, "UTC"), tclass = c("POSIXct", "POSIXt")), units = "secs", scale = "seconds", label = "second"), class = "periodicity") test_date <- as.Date("2022-10-15") info_msg <- "test.periodicity_on_one_observation_warns" x <- xts(1, .POSIXct(1, "UTC")) suppressWarnings(p <- periodicity(x)) expect_identical(p, P, info = info_msg) expect_warning(p <- periodicity(x), info = info_msg) info_msg <- "test.periodicity_on_zero_observations_warns" x <- xts(, .POSIXct(numeric(0), "UTC")) suppressWarnings(p <- periodicity(x)) P$start <- NA P$end <- NA expect_identical(p, P, info = info_msg) expect_warning(p <- periodicity(x)) check_periodicity_result <- function(p, units, scale, freq, msg) { info_msg <- paste0(msg, " - units: ", p$units, ", expected: ", units) expect_equivalent(p$units, units, info = info_msg) info_msg <- paste0(msg, " - scale: ", p$scale, ", expected: ", scale) expect_equivalent(p$scale, scale, info = info_msg) info_msg <- paste0(msg, " - frequency: ", p$frequency, ", expected: ", freq) expect_equivalent(p$frequency, freq, info = info_msg) info_msg <- paste0(msg, " - difftime: ", p$difftime, ", expected: ", freq) expect_equivalent(as.numeric(p$difftime), freq, info = info_msg) invisible(NULL) } ############################################################################### info_msg <- "test.periodicity_on_sub_second_data" set.seed(Sys.Date()) for (i in 1:100) { n <- sample(1000, 1) / 1000 #if (n >= eps) n <- 1 p <- periodicity(.xts(seq_len(100), n * seq_len(100))) check_periodicity_result(p, "secs", "seconds", n, info_msg) } # test periodicity between 0.95 and 1, which should round up to 1 #set.seed(Sys.Date()) #for (n in seq(0.9505, 0.99, 0.005)) { # p <- periodicity(.xts(seq_len(100), n * seq_len(100))) # check_periodicity_result(p, "secs", "seconds", n, info_msg) #} ############################################################################### info_msg <- "test.periodicity_on_second_data" i <- seq_len(100) for (n in 1:59) { p <- periodicity(.xts(i, i)) check_periodicity_result(p, "secs", "seconds", 1, info_msg) } ############################################################################### info_msg <- "test.periodicity_on_minute_data" i <- seq_len(100) * 60 for (n in 1:59) { p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "mins", "minute", n, info_msg) } ############################################################################### info_msg <- "test.periodicity_on_hourly_data" i <- seq_len(100) * 3600 for (n in 1:23) { p <- periodicity(.xts(i, n * i)) # NOTE: frequency is in seconds for hourly data (see #54) check_periodicity_result(p, "hours", "hourly", n * 3600, info_msg) } ############################################################################### info_msg <- "test.periodicity_on_daily_data" i <- seq_len(100) * 86400 # NOTE: frequency is in seconds for daily data (see #54) n <- 1 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "daily", n * 86400, info_msg) n <- 2 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "weekly", n * 86400, info_msg) n <- 3 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "weekly", n * 86400, info_msg) ############################################################################### info_msg <- "test.periodicity_on_weekly_data" i <- 7 * seq_len(100) * 86400 # NOTE: frequency is in seconds for weekly data (see #54) n <- 1 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "weekly", n * 86400 * 7, info_msg) n <- 2 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "monthly", n * 86400 * 7, info_msg) n <- 3 p <- periodicity(.xts(i, n * i)) check_periodicity_result(p, "days", "monthly", n * 86400 * 7, info_msg) ############################################################################### info_msg <- "test.periodicity_on_month_data" n <- 1 i <- seq(as.yearmon(test_date) - 12, by = n/12, length.out = 100) x <- xts(i, i) p <- periodicity(x) check_periodicity_result(p, "days", "monthly", 86400 * 31, info_msg) # monthly POSIXct index(x) <- as.POSIXct(i) p <- periodicity(x) check_periodicity_result(p, "days", "monthly", 86400 * 31, info_msg) n <- 2 i <- seq(as.yearmon(test_date) - 12, by = n/12, length.out = 100) x <- xts(i, i) p <- periodicity(x) check_periodicity_result(p, "days", "quarterly", 86400 * 61, info_msg) # monthly POSIXct index(x) <- as.POSIXct(i) p <- periodicity(x) check_periodicity_result(p, "days", "quarterly", 86400 * 61, info_msg) ############################################################################### info_msg <- "test.periodicity_on_quarter_data" n <- 1 i <- seq(as.yearqtr(test_date) - 24, by = n/4, length.out = 100) x <- xts(i, i) p <- periodicity(x) check_periodicity_result(p, "days", "quarterly", 86400 * 91, info_msg) # quarterly POSIXct index(x) <- as.POSIXct(i) p <- periodicity(x) check_periodicity_result(p, "days", "quarterly", 86400 * 91, info_msg) n <- 2 i <- seq(as.yearqtr(test_date) - 48, by = n/4, length.out = 100) p <- periodicity(xts(seq_len(100), i)) check_periodicity_result(p, "days", "yearly", 86400 * 183, info_msg) # quarterly POSIXct index(x) <- as.POSIXct(i) p <- periodicity(x) check_periodicity_result(p, "days", "yearly", 86400 * 183, info_msg) n <- 3 i <- seq(as.yearqtr(test_date) - 50, by = n/4, length.out = 100) p <- periodicity(xts(seq_len(100), i)) check_periodicity_result(p, "days", "yearly", 86400 * 274, info_msg) # quarterly POSIXct index(x) <- as.POSIXct(i) p <- periodicity(x) check_periodicity_result(p, "days", "yearly", 86400 * 274, info_msg) ############################################################################### ### These are the breakpoints in the code as-of 2022-10 ### Woe to the soul who breaks backward compatibility! info_msg <- "test.correct_units_for_edge_cases" test01 <- list(p = 59, units = "secs", scale = "seconds") test02 <- list(p = 60, units = "mins", scale = "minute") test03 <- list(p = 3600, units = "hours", scale = "hourly") test04 <- list(p = 86400 - 1, units = "hours", scale = "hourly") test05 <- list(p = 86400, units = "days", scale = "daily") test06 <- list(p = 604800 - 1, units = "days", scale = "weekly") test07 <- list(p = 2678400 - 1, units = "days", scale = "monthly") test08 <- list(p = 7948800 - 1, units = "days", scale = "quarterly") test09 <- list(p = 7948800, units = "days", scale = "quarterly") test10 <- list(p = 1 + 7948800, units = "days", scale = "yearly") result01 <- periodicity(.xts(, test01$p * seq_len(100))) result02 <- periodicity(.xts(, test02$p * seq_len(100))) result03 <- periodicity(.xts(, test03$p * seq_len(100))) result04 <- periodicity(.xts(, test04$p * seq_len(100))) result05 <- periodicity(.xts(, test05$p * seq_len(100))) result06 <- periodicity(.xts(, test06$p * seq_len(100))) result07 <- periodicity(.xts(, test07$p * seq_len(100))) result08 <- periodicity(.xts(, test08$p * seq_len(100))) result09 <- periodicity(.xts(, test09$p * seq_len(100))) result10 <- periodicity(.xts(, test10$p * seq_len(100))) expect_identical(test01$units, result01$units, info = do.call(paste, c(list(info_msg), test01))) expect_identical(test02$units, result02$units, info = do.call(paste, c(list(info_msg), test02))) expect_identical(test03$units, result03$units, info = do.call(paste, c(list(info_msg), test03))) expect_identical(test04$units, result04$units, info = do.call(paste, c(list(info_msg), test04))) expect_identical(test05$units, result05$units, info = do.call(paste, c(list(info_msg), test05))) expect_identical(test06$units, result06$units, info = do.call(paste, c(list(info_msg), test06))) expect_identical(test07$units, result07$units, info = do.call(paste, c(list(info_msg), test07))) expect_identical(test08$units, result08$units, info = do.call(paste, c(list(info_msg), test08))) expect_identical(test09$units, result09$units, info = do.call(paste, c(list(info_msg), test09))) expect_identical(test10$units, result10$units, info = do.call(paste, c(list(info_msg), test10))) info_msg <- "periodicity warns when 'x' is time-based and contains NA" x <- .Date(c(1:5, NA, 7:10)) expect_warning(periodicity(x), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-periodicity.R
# Tests for plotting functions data(sample_matrix) x <- as.xts(sample_matrix, dateFormat = "Date") # axTicksByTime info_msg <- "test.format_xts_yearqtr" xq <- to.quarterly(x) xtbt <- axTicksByTime(xq) expect_identical(names(xtbt), c("2007-Q1", "2007-Q2"), info = info_msg) info_msg <- "test.format_zoo_yearqtr" xq <- to.quarterly(x) xtbt <- axTicksByTime(as.zoo(xq)) expect_identical(names(xtbt), c("2007-Q1", "2007-Q2"), info = info_msg) info_msg <- "test.axTicksByTime_ticks.on_quarter" tick_marks <- setNames(c(1, 4, 7, 10, 13, 16, 19, 22, 25, 25), c("\nJan\n2016", "\nApr\n2016", "\nJul\n2016", "\nOct\n2016", "\nJan\n2017", "\nApr\n2017", "\nJul\n2017", "\nOct\n2017", "\nJan\n2018", "\nJan\n2018")) if (.Platform$OS.type != "unix") { names(tick_marks) <- gsub("\n(.*)\n", "\\1 ", names(tick_marks)) } ym <- as.yearmon("2018-01") - 24:0 / 12 x <- xts(seq_along(ym), ym) xtbt <- axTicksByTime(x, ticks.on = "quarters") expect_identical(xtbt, tick_marks, info = info_msg) info_msg <- "test.xlim_set_before_rendering" target <- c(86400.0, 864000.0) p <- plot(xts(1:10, .Date(1:10))) expect_equivalent(target, p$get_xlim(), info = info_msg) info_msg <- "test.ylim_set_before_rendering" x <- rnorm(10) p <- plot(xts(x, .Date(1:10))) expect_equivalent(range(x), p$get_ylim(), info = info_msg) get_xcoords_respects_object_tzone <- function() { # random timezone tz <- sample(OlsonNames(), 1) dttm <- seq(as.POSIXct("2023-01-01 01:23:45"), , 1, 5) x <- xts(c(5, 1, 2, 4, 3), dttm, tzone = tz) print(p <- plot(x)) expect_identical(tz, tzone(p$get_xcoords(x)), info = paste("TZ =", tz)) } get_xcoords_respects_object_tzone()
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-plot.R
x <- xts(cbind(1:10, 1:10), .Date(1:10)) # NOTE: expected value is (2 + 2) to account for # (1) column header: " [,1] [,2]" # (2) message: "[ reached getOption("max.print") -- omitted 6 rows ]" print_output <- utils::capture.output(print(x, max = 4)) expect_true(length(print_output) == (2 + 2), info = "'max' argument is respected'") print_output <- utils::capture.output(print(x, max = 4, show.nrows = 10)) expect_true(length(print_output) == (2 + 2), info = "'max' takes precedence over 'show.nrows'") expect_silent(p <- print(drop(x[, 1])), info = "print.xts() does not error when object doesn't have dims") print_output <- utils::capture.output(print(drop(x[1:2, 1]))) expect_true(all(grepl("1970-01", print_output[-1])), info = "print.xts() output shows index when object doesn't have dims") # 'show.nrows' > 'trunc.rows' print_output <- utils::capture.output(print(x, show.nrows = 10, trunc.rows = 4)) expect_true(length(print_output)-1 == nrow(x), info = "print.xts() shows correct number of rows when show.nrows > trunc.rows") y <- xts(cbind(1:11, 1:11), .Date(1:11)) show_nrows <- floor(nrow(y) / 2) print_output <- utils::capture.output(print(y, show.nrows = show_nrows, trunc.rows = nrow(y)-2)) expect_true(length(print_output)-1 == 2*show_nrows+1, info = "print.xts() shows correct number of rows when show.nrows < trunc.rows / 2") show_nrows <- ceiling(nrow(y) / 2) print_output <- utils::capture.output(print(y, show.nrows = show_nrows, trunc.rows = nrow(y)-2)) expect_true(length(print_output)-1 == nrow(y), info = "print.xts() shows correct number of rows when show.nrows > trunc.rows / 2") print_output <- utils::capture.output(p <- print(x)) expect_identical(p, x, info = "returns input invisibly") z <- .xts(matrix(0, nrow = 200, ncol = 200), 1:200) expect_silent(print(z), info = "print more columns than width doesn't error") expect_silent(print(x, quote = TRUE), info = "print.xts() does not error when 'quote' argument is used") expect_silent(print(x, right = TRUE), info = "print.xts() does not error when 'right' argument is used")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-print.R
# ensure reclass() preserves index attributes from 'match.to' info_msg <- "test.reclass_preserves_match.to_tclass" x <- .xts(1:3, 1:3, tclass = "Date") y <- reclass(1:3, match.to = x) expect_identical(tclass(y), "Date", info = info_msg) info_msg <- "test.reclass_preserves_match.to_tzone" tz <- "Atlantic/Reykjavik" x <- .xts(1:3, 1:3, tzone = tz) y <- reclass(1:3, match.to = x) expect_identical(tzone(y), tz, info = info_msg) info_msg <- "test.reclass_preserves_match.to_tformat" tf <- "%m/%d/%Y %H:%M" x <- .xts(1:3, 1:3, tformat = tf) y <- reclass(1:3, match.to = x) expect_identical(tformat(y), tf, info = info_msg) info_msg <- "test.reclass_preserves_match.to_xtsAttributes" xts_attr <- list("hello" = "world") x <- .xts(1:3, 1:3) xtsAttributes(x) <- xts_attr z <- reclass(1:3, match.to = x) expect_equal(xts_attr, xtsAttributes(z), info = info_msg) # ensure reclass(xts_object, ...) preserves match.to attributes info_msg <- "test.reclass_xts_object_preserves_match.to_tclass" x <- y <- xts(1:3, .Date(1:3)) tclass(x) <- c("POSIXct", "POSIXt") z <- reclass(x, y) expect_identical(tclass(y), tclass(z), info = info_msg) info_msg <- "test.reclass_xts_object_preserves_match.to_tzone" x <- y <- xts(1:3, .Date(1:3)) tz <- "Atlantic/Reykjavik" tzone(x) <- tz z <- reclass(x, y) expect_identical("UTC", tzone(z), info = info_msg) info_msg <- "test.reclass_xts_object_preserves_match.to_tformat" tf <- "%m/%d/%Y" x <- y <- xts(1:3, .Date(1:3), tformat = tf) tformat(x) <- "%Y-%m-%d" z <- reclass(x, y) expect_identical(tf, tformat(z), info = info_msg) info_msg <- "test.reclass_xts_object_preserves_match.to_xtsAttributes" x <- y <- xts(1:3, .Date(1:3)) xts_attr <- list("hello" = "world") xtsAttributes(y) <- xts_attr z <- reclass(x, y) expect_equal(xts_attr, xtsAttributes(z), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-reclass.R
nm_minutes <- c("1970-01-01 00:00:00", "1970-01-01 00:01:00") # 'f' is character, but length(f) > 1 info_msg <- "test.split_character_f_not_endpoints" x <- .xts(1:5, 1:5) f <- letters[1:nrow(x)] expect_identical(split(x,f), split(as.zoo(x),f), info = info_msg) info_msg <- "test.split_returns_named_list" qtr_2020 <- paste0("2020 Q", 1:4) qtr_2021 <- paste0("2021 Q", 1:4) info_msg <- "quarterly data split by year" x_q <- xts(1:8, as.yearqtr(c(qtr_2020, qtr_2021))) nm_q <- names(split(x_q, "years")) expect_identical(c("2020", "2021"), nm_q, info = info_msg) # names formatted as yearqtr info_msg <- "monthly data split by quarter" x_mo <- xts(1:12, as.yearmon(2020 + 0:11/12)) nm_mo <- names(split(x_mo, "quarters")) expect_identical(qtr_2020, nm_mo, info = info_msg) # names formatted as yearmon info_msg <- "daily data split by month" x_day <- xts(1:10, .Date(-5:4)) nm_day <- names(split(x_day, "months")) expect_identical(c("Dec 1969", "Jan 1970"), nm_day, info = info_msg) # names formatted as Date info_msg <- "hourly data split by day" x_hr <- .xts(1:10, -5:4 * 3600, tzone = "UTC") nm_hr <- names(split(x_hr, "days")) expect_identical(c("1969-12-31", "1970-01-01"), nm_hr, info = info_msg) info_msg <- "second data split by minute" x_sec <- .xts(1:120, 1:120 - 1, tzone = "UTC") nm_sec <- names(split(x_sec, "minutes")) expect_identical(nm_minutes, nm_sec, info = info_msg) if (.Machine$sizeof.pointer == 8) { # only run on 64-bit systems because this fails on 32-bit systems due to # precision issues # # ?.Machine says: # sizeof.pointer: the number of bytes in a C 'SEXP' type. Will be '4' on # 32-bit builds and '8' on 64-bit builds of R. info_msg <- "microsecond data split by milliseconds" t1 <- as.POSIXct(nm_minutes[1], tz = "UTC") us <- seq(1e-4, 2e-1, 1e-4) x_us <- xts(seq_along(us), t1 + us) nm_ms <- names(split(x_us, "milliseconds")) nm_target <- format(t1 + seq(0, 0.2, 0.001), "%Y-%m-%d %H:%M:%OS3") expect_identical(nm_target, nm_ms, info = info_msg) } # names correct when object TZ vs GMT are on different sides of split breaks (#392) info_msg <- "yearmon: object TZ and GMT are different days" x_tz <- .xts(1:3, c(1632481200, 1633042800, 1635724800), tzone = "Europe/Berlin") expect_identical(names(split(x_tz, "months")), paste(c("Sep", "Oct", "Nov"), "2021"), info = info_msg) info_msg <- "yearqtr: object TZ and GMT are different days" expect_identical(names(split(x_tz, "quarters")), c("2021 Q3", "2021 Q4"), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-split.R
# Time-of-day subset tests info_msg <- "test.time_of_day_start_equals_end" i <- 0:47 x <- .xts(i, i * 3600, tzone = "UTC") i1 <- .index(x[c(2L, 26L)]) expect_identical(.index(x["T01:00/T01:00"]), i1, info = info_msg) info_msg <- "test.time_of_day_when_DST_starts" # 2017-03-12: no 0200 tz <- "America/Chicago" tmseq <- seq(as.POSIXct("2017-03-11", tz), as.POSIXct("2017-03-14", tz), by = "1 hour") x <- xts(seq_along(tmseq), tmseq) i <- structure(c(1489215600, 1489219200, 1489222800, 1489302000, 1489305600, 1489384800, 1489388400, 1489392000), tzone = "America/Chicago", tclass = c("POSIXct", "POSIXt")) expect_identical(.index(x["T01:00:00/T03:00:00"]), i, info = info_msg) info_msg <- "test.time_of_day_when_DST_ends" # 2017-11-05: 0200 occurs twice tz <- "America/Chicago" tmseq <- seq(as.POSIXct("2017-11-04", tz), as.POSIXct("2017-11-07", tz), by = "1 hour") x <- xts(seq_along(tmseq), tmseq) i <- structure(c(1509775200, 1509778800, 1509782400, 1509861600, 1509865200, 1509868800, 1509872400, 1509951600, 1509955200, 1509958800), tzone = "America/Chicago", tclass = c("POSIXct", "POSIXt")) expect_identical(.index(x["T01:00:00/T03:00:00"]), i, info = info_msg) info_msg <- "test.time_of_day_by_hour_start_equals_end" i <- 0:94 x <- .xts(i, i * 1800, tzone = "UTC") i1 <- .index(x[c(3, 4, 51, 52)]) expect_identical(.index(x["T01/T01"]), i1, info = info_msg) expect_identical(.index(x["T1/T1"]), i1, info = info_msg) info_msg <- "test.time_of_day_by_minute" i <- 0:189 x <- .xts(i, i * 900, tzone = "UTC") i1 <- .index(x[c(5:8, 101:104)]) expect_identical(.index(x["T01:00/T01:45"]), i1, info = info_msg) expect_identical(.index(x["T01/T01:45"]), i1, info = info_msg) info_msg <- "test.time_of_day_check_time_string" i <- 0:10 x <- .xts(i, i * 1800, tzone = "UTC") # Should work with and without colon separator expect_identical(x["T0100/T0115"], x["T01:00/T01:15"], info = info_msg) info_msg <- "test.time_of_day_by_second" i <- 0:500 x <- .xts(c(i, i), c(i * 15, 86400 + i * 15), tzone = "UTC") i1 <- .index(x[c(474L, 475L, 476L, 477L, 478L, 479L, 480L, 481L, 482L, 483L, 484L, 485L, 975L, 976L, 977L, 978L, 979L, 980L, 981L, 982L, 983L, 984L, 985L, 986L)]) expect_identical(.index(x["T01:58:05/T02:01:09"]), i1, info = info_msg) # Can only omit 0 padding for hours. Only for convenience because it does # not conform to the ISO 8601 standard, which requires padding with zeros. expect_identical(.index(x["T1:58:05/T2:01:09"]), i1, info = info_msg) expect_identical(.index(x["T1:58:05.000/T2:01:09.000"]), i1, info = info_msg) info_msg <- "test.time_of_day_end_before_start" # Yes, this actually makes sense and is useful for financial markets # E.g. some futures markets open at 18:00 and close at 16:00 the next day i <- 0:47 x <- .xts(i, i * 3600, tzone = "UTC") i1 <- .index(x[-c(18L, 42L)]) expect_identical(.index(x["T18:00/T16:00"]), i1, info = info_msg) # TODO: Add tests for possible edge cases and/or errors # end time before start time # start time and/or end time missing "T" prefix info_msg <- "test.time_of_day_on_zero_width" # return relevant times and a column of NA; consistent with zoo i <- 0:47 tz <- "America/Chicago" x <- .xts(, i * 3600, tzone = tz) y <- x["T18:00/T20:00"] expect_identical(y, .xts(rep(NA, 6), c(0:2, 24:26)*3600, tzone = tz), info = info_msg) info_msg <- "test.time_of_day_zero_padding" i <- 0:189 x <- .xts(i, i * 900, tzone = "UTC") i1 <- .index(x[c(5:8, 101:104)]) expect_identical(.index(x["T01:00/T01:45"]), i1, info = info_msg) # we support un-padded hours, for convenience (it's not in the standard) expect_identical(.index(x["T1/T1:45"]), i1, info = info_msg) # minutes and seconds must be zero-padded expect_error(x["T01:5:5/T01:45"], info = info_msg) expect_error(x["T01:05:5/T01:45"], info = info_msg) info_msg <- "test.open_ended_time_of_day" ix <- seq(.POSIXct(0), .POSIXct(86400 * 5), by = "sec") ix <- ix + runif(length(ix)) x <- xts::xts(seq_along(ix), ix) expect_true(all(xts::.indexhour(x["T1800/"]) > 17), info = paste(info_msg, "right open")) expect_true(all(xts::.indexhour(x["/T0500"]) < 6), info = paste(info_msg, "left open"))
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-subset-time-of-day.R
### i = missing, j = NA, object has column names ### See #181 info_msg <- "test.i_missing_j_NA_has_colnames" iina <- .xts(matrix(NA_integer_, 5, 2), 1:5) idna <- .xts(matrix(NA_integer_, 5, 2), 1.0 * 1:5) dina <- .xts(matrix(NA_real_, 5, 2), 1:5) ddna <- .xts(matrix(NA_real_, 5, 2), 1.0 * 1:5) colnames(iina) <- colnames(idna) <- colnames(dina) <- colnames(ddna) <- rep(NA_character_, 2) # int data, int index ii <- .xts(matrix(1:10, 5, 2), 1:5) colnames(ii) <- c("a", "b") expect_identical(ii[, NA], iina, info = paste(info_msg, "int data, int index")) expect_identical(ii[, 1][, NA], iina[, 1], info = paste(info_msg, "int data, int index")) # int data, dbl index id <- .xts(matrix(1:10, 5, 2), 1.0 * 1:5) colnames(id) <- c("a", "b") expect_identical(id[, NA], idna, info = paste(info_msg, "int data, dbl index")) expect_identical(id[, 1][, NA], idna[, 1], info = paste(info_msg, "int data, dbl index")) # dbl data, int index di <- .xts(1.0 * matrix(1:10, 5, 2), 1:5) colnames(di) <- c("a", "b") expect_identical(di[, NA], dina, info = paste(info_msg, "dbl data, int index")) expect_identical(di[, 1][, NA], dina[, 1], info = paste(info_msg, "dbl data, int index")) # dbl data, dbl index dd <- .xts(1.0 * matrix(1:10, 5, 2), 1.0 * 1:5) colnames(dd) <- c("a", "b") expect_identical(dd[, NA], ddna, info = paste(info_msg, "dbl data, dbl index")) expect_identical(dd[, 1][, NA], ddna[, 1], info = paste(info_msg, "dbl data, dbl index")) ### i = missing, j = NA, object does not have column names ### See #97 info_msg <- "test.i_missing_j_NA_no_colnames" iina <- .xts(matrix(NA_integer_, 5, 2), 1:5) idna <- .xts(matrix(NA_integer_, 5, 2), 1.0 * 1:5) dina <- .xts(matrix(NA_real_, 5, 2), 1:5) ddna <- .xts(matrix(NA_real_, 5, 2), 1.0 * 1:5) # int data, int index ii <- .xts(matrix(1:10, 5, 2), 1:5) expect_identical(ii[, NA], iina, info = paste(info_msg, "int data, int index")) expect_identical(ii[, 1][, NA], iina[, 1], info = paste(info_msg, "int data, int index")) # int data, dbl index id <- .xts(matrix(1:10, 5, 2), 1.0 * 1:5) expect_identical(id[, NA], idna, info = paste(info_msg, "int data, dbl index")) expect_identical(id[, 1][, NA], idna[, 1], info = paste(info_msg, "int data, dbl index")) # dbl data, int index di <- .xts(1.0 * matrix(1:10, 5, 2), 1:5) expect_identical(di[, NA], dina, info = paste(info_msg, "dbl data, int index")) expect_identical(di[, 1][, NA], dina[, 1], info = paste(info_msg, "dbl data, int index")) # dbl data, dbl index dd <- .xts(1.0 * matrix(1:10, 5, 2), 1.0 * 1:5) expect_identical(dd[, NA], ddna, info = paste(info_msg, "dbl data, dbl index")) expect_identical(dd[, 1][, NA], ddna[, 1], info = paste(info_msg, "dbl data, dbl index")) ### i = integer, j = NA, object has column names ### See #97 info_msg <- "test.i_integer_j_NA_has_colnames" iina <- .xts(matrix(NA_integer_, 5, 2), 1:5) idna <- .xts(matrix(NA_integer_, 5, 2), 1.0 * 1:5) dina <- .xts(matrix(NA_real_, 5, 2), 1:5) ddna <- .xts(matrix(NA_real_, 5, 2), 1.0 * 1:5) colnames(iina) <- colnames(idna) <- colnames(dina) <- colnames(ddna) <- rep(NA_character_, 2) i <- 1:3 # int data, int index ii <- .xts(matrix(1:10, 5, 2), 1:5) colnames(ii) <- c("a", "b") expect_identical(ii[i, NA], iina[i,], info = paste(info_msg, "int data, int index")) expect_identical(ii[i, 1][, NA], iina[i, 1], info = paste(info_msg, "int data, int index")) # int data, dbl index id <- .xts(matrix(1:10, 5, 2), 1.0 * 1:5) colnames(id) <- c("a", "b") expect_identical(id[i, NA], idna[i,], info = paste(info_msg, "int data, dbl index")) expect_identical(id[i, 1][, NA], idna[i, 1], info = paste(info_msg, "int data, dbl index")) # dbl data, int index di <- .xts(1.0 * matrix(1:10, 5, 2), 1:5) colnames(di) <- c("a", "b") expect_identical(di[i, NA], dina[i,], info = paste(info_msg, "dbl data, int index")) expect_identical(di[i, 1][, NA], dina[i, 1], info = paste(info_msg, "dbl data, int index")) # dbl data, dbl index dd <- .xts(1.0 * matrix(1:10, 5, 2), 1.0 * 1:5) colnames(dd) <- c("a", "b") expect_identical(dd[i, NA], ddna[i,], info = paste(info_msg, "dbl data, dbl index")) expect_identical(dd[i, 1][, NA], ddna[i, 1], info = paste(info_msg, "dbl data, dbl index")) ### i = integer, j = NA, object does not have column names ### See #97 info_msg <- "test.i_integer_j_NA_no_colnames" iina <- .xts(matrix(NA_integer_, 5, 2), 1:5) idna <- .xts(matrix(NA_integer_, 5, 2), 1.0 * 1:5) dina <- .xts(matrix(NA_real_, 5, 2), 1:5) ddna <- .xts(matrix(NA_real_, 5, 2), 1.0 * 1:5) i <- 1:3 # int data, int index ii <- .xts(matrix(1:10, 5, 2), 1:5) expect_identical(ii[i, NA], iina[i,], info = paste(info_msg, "int data, int index")) expect_identical(ii[i, 1][, NA], iina[i, 1], info = paste(info_msg, "int data, int index")) # int data, dbl index id <- .xts(matrix(1:10, 5, 2), 1.0 * 1:5) expect_identical(id[i, NA], idna[i,], info = paste(info_msg, "int data, dbl index")) expect_identical(id[i, 1][, NA], idna[i, 1], info = paste(info_msg, "int data, dbl index")) # dbl data, int index di <- .xts(1.0 * matrix(1:10, 5, 2), 1:5) expect_identical(di[i, NA], dina[i,], info = paste(info_msg, "dbl data, int index")) expect_identical(di[i, 1][, NA], dina[i, 1], info = paste(info_msg, "dbl data, int index")) # dbl data, dbl index dd <- .xts(1.0 * matrix(1:10, 5, 2), 1.0 * 1:5) expect_identical(dd[i, NA], ddna[i,], info = paste(info_msg, "dbl data, dbl index")) expect_identical(dd[i, 1][, NA], ddna[i, 1], info = paste(info_msg, "dbl data, dbl index")) info_msg <- "test.i_0" x <- .xts(matrix(1:10, 5, 2), 1:5) z <- as.zoo(x) xz0 <- as.xts(z[0,]) expect_equal(x[0,], xz0, info = info_msg) ### Subset by non-numeric classes X <- xts(1:5, as.Date("2018-04-21") - 5:1) info_msg <- "test.i_character" x <- X for (r in c(1L, 3L, 5L)) { y <- x[r,] i <- as.character(index(y)) expect_identical(y, x[i, ], info = paste(info_msg, "i =", r)) } info_msg <- "test.i_asis_character" x <- X for (r in c(1L, 3L, 5L)) { y <- x[r,] i <- as.character(index(y)) expect_identical(y, x[I(i), ], info = paste(info_msg, "r =", r)) } info_msg <- "test.i_Date" x <- X for (r in c(1L, 3L, 5L)) { y <- x[r,] i <- index(y) expect_identical(y, x[i, ], info = paste(info_msg, "r =", r)) } info_msg <- "test.i_POSIXct" x <- X index(x) <- as.POSIXct(index(x), tz = "UTC") for (r in c(1L, 3L, 5L)) { y <- x[r,] i <- index(y) expect_identical(y, x[i, ], info = paste(info_msg, "r =", r)) } info_msg <- "test.i_POSIXlt" x <- X index(x) <- as.POSIXlt(index(x), tz = "UTC") for (r in c(1L, 3L, 5L)) { y <- x[r,] i <- index(y) expect_identical(y, x[i, ], info = paste(info_msg, "r =", r)) } ### invalid date/time info_msg <- "test.i_invalid_date_string" x <- xts(1:10, as.Date("2015-02-20")+0:9) expect_warning(y <- x["2012-02-30"], pattern = "cannot determine first and last time") expect_identical(y, x[NA,], info = info_msg) info_msg <- "test.i_only_range_separator_or_empty_string" x <- xts(1:10, as.Date("2015-02-20")+0:9) y <- x["/",] expect_identical(y, x, info = paste(info_msg, "sep = '/'")) y <- x["::",] expect_identical(y, x, info = paste(info_msg, "sep = '::'")) y <- x["",] expect_identical(y, x, info = paste(info_msg, "sep = ''")) info_msg <- "test.i_date_range_open_end" x <- xts(1:10, as.Date("2015-02-20")+0:9) y <- x["2015-02-23/",] expect_identical(y, x[4:10,], info = info_msg) info_msg <- "test.i_date_range_open_start" x <- xts(1:10, as.Date("2015-02-20")+0:9) y <- x["/2015-02-26",] expect_identical(y, x[1:7,], info = info_msg) ### subset empty xts info_msg <- "empty xts subset by datetime matches zoo" d0 <- as.Date(integer()) zl <- xts(, d0) empty <- as.xts(as.zoo(zl)[i,]) i <- Sys.Date() expect_identical(zl[i,], empty, info = paste(info_msg, "i = Date, [i,]")) expect_identical(zl[i], empty, info = paste(info_msg, "i = Date, [i]")) i <- Sys.time() expect_identical(zl[i,], empty, info = paste(info_msg, "i = POSIXct, [i,]")) expect_identical(zl[i], empty, info = paste(info_msg, "i = POSIXct, [i]")) info_msg <- "empty xts subset by 0 matches zoo" d0 <- as.Date(integer()) zl <- xts(, d0) empty <- as.xts(as.zoo(zl)[0,]) expect_identical(zl[0,], empty, info = paste(info_msg, "[i,]")) expect_identical(zl[0], empty, info = paste(info_msg, "[i]")) info_msg <- "empty xts subset by -1 matches zoo" d0 <- as.Date(integer()) zl <- xts(, d0) empty <- as.xts(as.zoo(zl)[i,]) expect_identical(zl[-1,], empty, info = paste(info_msg, "[-1,]")) expect_identical(zl[-1], empty, info = paste(info_msg, "[-1]")) info_msg <- "empty xts subset by NA matches zoo" d0 <- as.Date(integer()) zl <- xts(, d0) empty <- as.xts(as.zoo(zl)[i,]) expect_identical(zl[NA,], empty, info = paste(info_msg, "[NA,]")) expect_identical(zl[NA], empty, info = paste(info_msg, "[NA]")) info_msg <- "empty xts subset by NULL matches zoo" d0 <- as.Date(integer()) zl <- xts(, d0) empty <- as.xts(as.zoo(zl)[i,]) expect_identical(zl[NULL,], empty, info = paste(info_msg, "[NULL,]")) expect_identical(zl[NULL], empty, info = paste(info_msg, "[NULL]")) info_msg <- "test.duplicate_index_duplicate_i" dates <- structure(c(15770, 16257, 16282, 16291, 16296, 16296, 16298, 16301, 16432, 16452), class = "Date") x <- xts(c(1, 2, 2, 3, 3, 3, 3, 3, 4, 4), dates) dupdates <- structure(c(15770, 16257, 16282, 16291, 16296, 16296, 16296, 16296, 16298, 16301, 16432, 16452), class = "Date") y <- xts(c(1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4), dupdates) expect_identical(x[index(x),], y, info = info_msg) ### Test dispatch to zoo for yearmon, yearqtr tclass info_msg <- "test.window_yearmon_yearqtr_tclass_dispatches_to_zoo" i1 <- seq(as.yearmon(2007), by = 1/12, length.out = 36) x1 <- xts(1:36, i1) i2 <- seq(as.yearqtr(2007), by = 1/4, length.out = 36) x2 <- xts(1:36, i2) r1 <- x1["2015"] r2 <- x2["2015"] ########## results are empty objects ########## ### zoo supports numeric start for yearmon and yearqtr w1 <- window(x1, start = 2015.01) # to window.zoo() w2 <- window(x2, start = 2015.1) # to window.zoo() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, numeric start, empty range")) expect_equal(r2, w2, info = paste(info_msg, "window, yearqtr, numeric start, empty range")) w1 <- window(x1, start = "2015-01-01") # to window.xts() w2 <- window(x2, start = "2015Q1") # to window.zoo() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, character start, empty range")) expect_equal(r2, w2, info = paste(info_msg, "window, yearqtr, character start, empty range")) w1 <- window(x1, start = "2015-01-01", end = NA) # to window.xts() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, character start with end = NA, empty range")) ########## results are *not* empty objects ########## r1 <- x1["2011/"] r2 <- x2["2011/"] w1 <- window(x1, start = 2011.01) # to window.zoo() w2 <- window(x2, start = 2011.1) # to window.zoo() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, numeric start")) expect_equal(r2, w2, info = paste(info_msg, "window, yearqtr, numeric start")) w1 <- window(x1, start = "2011-01-01") # to window.xts() w2 <- window(x2, start = "2011Q1") # to window.zoo() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, character start")) expect_equal(r2, w2, info = paste(info_msg, "window, yearqtr, character start")) w1 <- window(x1, start = "2011-01-01", end = NA) # to window.xts() expect_equal(r1, w1, info = paste(info_msg, "window, yearmon, character start with end = NA")) info_msg <- "test.zero_width_subset_does_not_drop_class" target <- c("custom", "xts", "zoo") x <- .xts(1:10, 1:10, class = target) y <- x[,0] expect_equal(target, class(y), info = info_msg) info_msg <- "test.zero_width_subset_does_not_drop_user_attributes" x <- .xts(1:10, 1:10, my_attr = "hello") y <- x[,0] expect_equal("hello", attr(y, "my_attr"), info = info_msg) info_msg <- "test.zero_length_subset_xts_returns_same_tclass" x <- .xts(matrix(1)[0,], integer(0), "Date") expect_equal(tclass(x[0,]), "Date") x <- .xts(matrix(1)[0,], integer(0), "POSIXct", "America/Chicago") expect_equal(tclass(x[0,]), "POSIXct") expect_equal(tzone(x[0,]), "America/Chicago") info_msg <- "test.zero_length_subset_returns_same_storage_mode" tf <- c(TRUE, FALSE) # integer sm <- "integer" x <- .xts(matrix(integer(0), 0), integer(0)) expect_equal(storage.mode(x[0, ]), sm, info = paste(info_msg, ": x[0,]")) expect_equal(storage.mode(x[0, 0]), sm, info = paste(info_msg, ": x[0, 0")) expect_equal(storage.mode(x[0, FALSE]), sm, info = paste(info_msg, ": x[0, FALSE]")) x <- .xts(matrix(integer(0), 0, 2), integer(0)) expect_equal(storage.mode(x[0,]), sm, info = paste(info_msg, ": x[0,]")) expect_equal(storage.mode(x[0, 1]), sm, info = paste(info_msg, ": x[0, 1]")) expect_equal(storage.mode(x[0, tf]), sm, nfo = paste(info_msg, ": x[0, c(TRUE, FALSE)]")) # double sm <- "double" x <- .xts(matrix(numeric(0), 0), integer(0)) expect_equal(storage.mode(x[0, ]), sm, info = paste(info_msg, ": x[0,]")) expect_equal(storage.mode(x[0, 0]), sm, info = paste(info_msg, ": x[0, 0]")) expect_equal(storage.mode(x[0, FALSE]), sm, info = paste(info_msg, ": x[0, FALSE]")) x <- .xts(matrix(numeric(0), 0, 2), integer(0)) expect_equal(storage.mode(x[0,]), sm, info = paste(info_msg, ": x[0,]")) expect_equal(storage.mode(x[0, 1]), sm, info = paste(info_msg, ": x[0, 1]")) expect_equal(storage.mode(x[0, tf]), sm, info = paste(info_msg, ": x[0, c(TRUE, FALSE)]"))
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-subset.R
# These tests check the time class attribute is attached to the expected # component of the xts object. The xts constructors should no longer add # 'tclass' or '.indexClass' attributes to the xts object itself. Only the index # should have a 'tclass' attribute. Construct xts objects using structure() to # test behavior when functions encounter xts objects created before 0.10-3. x <- structure(1:5, .Dim = c(5L, 1L), index = structure(1:5, tzone = "", tclass = c("POSIXct", "POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "UTC", tzone = "UTC", class = c("xts", "zoo")) info_msg <- "tclass(x) gets tclass attribute from index, not the xts object" expect_identical(tclass(x), c("POSIXct", "POSIXt"), info = info_msg) info_msg <- "indexClass(x) warns" expect_warning(indexClass(x), info = info_msg) info_msg <- "indexClass(x) <- 'Date' warns" expect_warning(indexClass(x) <- "Date", info = info_msg) info_msg <- "tclass(x) <- 'POSIXct' removes tclass and .indexCLASS from xts object" y <- x tclass(y) <- "POSIXct" expect_identical(NULL, attr(y, "tclass"), info = info_msg) expect_identical(NULL, attr(y, ".indexCLASS"), info = info_msg) info_msg <- "tclass<- sets tclass attribute on index" y <- x tclass(y) <- "Date" expect_identical("Date", attr(attr(y, "index"), "tclass"), info = info_msg) info_msg <- "tclass<- removes .indexCLASS attribute from xts object" expect_identical("Date", attr(.index(y), "tclass"), info = info_msg) info_msg <- "coredata(x) removes tclass and .indexCLASS from xts object" y <- coredata(x) expect_identical(NULL, attr(y, "tclass"), info = info_msg) expect_identical(NULL, attr(y, ".indexCLASS"), info = info_msg) info_msg <- "xtsAttributes(x) does not include tclass or .indexCLASS" y <- xtsAttributes(x) expect_identical(NULL, y$tclass, info = info_msg) expect_identical(NULL, y$.indexCLASS, info = info_msg) info_msg <- "xtsAttributes(x) <- 'foo' removes tclass and .indexCLASS" y <- x xtsAttributes(y) <- xtsAttributes(x) expect_identical(NULL, attr(y, "tclass"), info = info_msg) expect_identical(NULL, attr(y, ".indexCLASS"), info = info_msg) info_msg <- "tclass(x) <- `foo` always creates a character tclass" x <- "hello" tclass(x) <- 1 expect_identical(storage.mode(attr(x, "tclass")), "character") info_msg <- "zero-width subset has the same tclass as the input" target <- "Imatclass" x <- .xts(1:10, 1:10, tclass = target) y <- x[,0] expect_equal(target, tclass(y)) info_msg <- "tclass() on object with no tclass/.indexCLASS returns POSIXct" x <- structure(1:5, .Dim = c(5L, 1L), index = 1:5, class = c("xts", "zoo")) expect_warning(xtc <- tclass(x), "index does not have a 'tclass' attribute") expect_identical(c("POSIXct", "POSIXt"), xtc) info_msg <- "tclass<-() updates index" x <- xts(1, .POSIXct(14400, tz = "Europe/Berlin")) tclass(x) <- "Date" expect_identical(as.numeric(.index(x)), 0, info = paste(info_msg, "values")) expect_identical(tzone(x), "UTC", info = paste(info_msg, "timezone"))
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-tclass.R
# These tests check the 'tformat' attribute is attached to the expected # component of the xts object. The xts constructors should no longer add the # '.indexFORMAT' attribute to the xts object itself. Only the index should # have a 'tformat' attribute. Construct xts objects using structure() to # test behavior when functions encounter xts objects created before 0.10-3. x <- structure(1:5, .Dim = c(5L, 1L), index = structure(1:5, tzone = "", tclass = c("POSIXct", "POSIXt"), tformat = "%Y-%m-%d"), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "UTC", tzone = "UTC", .indexFORMAT = "%Y-%m-%d %H:%M:%S", class = c("xts", "zoo")) info_msg <- "test.get_tformat" expect_identical(tformat(x), "%Y-%m-%d", info = info_msg) info_msg <- "test.get_indexFORMAT_warns" expect_warning(indexFormat(x), info = info_msg) info_msg <- "test.set_indexFORMAT_warns" expect_warning(indexFormat(x) <- "GMT", info = info_msg) info_msg <- "test.set_tformat_drops_xts_indexFORMAT" y <- x tformat(y) <- "%Y-%m-%d %H:%M" expect_identical(NULL, attr(y, ".indexFORMAT"), info = info_msg) info_msg <- "test.set_tformat_changes_index_tformat" y <- x fmt <- "%Y-%m-%d %H:%M" tformat(y) <- fmt expect_identical(fmt, attr(attr(y, "index"), "tformat"), info = info_msg) info_msg <- "test.get_coredata_drops_xts_indexFORMAT" y <- coredata(x) expect_identical(NULL, attr(y, ".indexFORMAT"), info = info_msg) info_msg <- "test.get_xtsAttributes_excludes_indexFORMAT" y <- xtsAttributes(x) expect_identical(NULL, y$.indexFORMAT, info = info_msg) info_msg <- "test.set_xtsAttributes_removes_indexFORMAT" y <- x xtsAttributes(y) <- xtsAttributes(x) expect_identical(NULL, attr(y, ".indexFORMAT"), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-tformat.R
# timeBasedSeq tests # 1999 to 2008 by year, Date info_msg <- "test.tbs_1999_to_2008_by_year_Date" tbs <- timeBasedSeq('1999/2008') bench <- seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='year') expect_equivalent(tbs, bench, info = info_msg) # 1999 to 2008 by year, retclass='Date' info_msg <- "test.tbs_1999_to_2008_by_year_retclassDate" tbs <- timeBasedSeq('1999/2008', retclass='Date') bench <- seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='year') expect_equivalent(tbs, bench, info = info_msg) # 1999 to 2008 by year, retclass="POSIXct" info_msg <- "test.tbs_1999_to_2008_by_year" tbs <- timeBasedSeq('1999/2008',retclass='POSIXct') bench <- seq(as.POSIXct("1999-01-01"),as.POSIXct("2008-01-01"),by='year') expect_equivalent(tbs, bench, info = info_msg) # MONTHLY sequences # defaults to yearmon from the zoo package # NB: these differ by ~4.16e-5 on Solaris and rhub's windows-x86_64-devel info_msg <- "test.tbs_199901_to_200801_by_month" tbs <- timeBasedSeq('199901/200801') bench <- as.yearmon(seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='month')) expect_equivalent(tbs, bench, tolerance = 1e-4, info = info_msg) info_msg <- "test.tbs_199901_to_2008_by_month" tbs <- timeBasedSeq('199901/2008') bench <- as.yearmon(seq(as.Date("1999-01-01"),as.Date("2008-12-01"),by='month')) expect_equivalent(tbs, bench, tolerance = 1e-4, info = info_msg) info_msg <- "test.tbs_1999_to_200801_by_month" tbs <- timeBasedSeq('1999/200801') bench <- as.yearmon(seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='month')) expect_equivalent(tbs, bench, tolerance = 1e-4, info = info_msg) # retclass=Date info_msg <- "test.tbs_199901_to_200801_by_month_Date" tbs <- timeBasedSeq('199901/200801', retclass='Date') bench <- seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='month') expect_equivalent(tbs, bench, info = info_msg) info_msg <- "test.tbs_199901_to_2008_by_month_Date" tbs <- timeBasedSeq('199901/2008', retclass='Date') bench <- seq(as.Date("1999-01-01"),as.Date("2008-12-01"),by='month') expect_equivalent(tbs, bench, info = info_msg) info_msg <- "test.tbs_1999_to_200801_by_month_Date" tbs <- timeBasedSeq('1999/200801', retclass='Date') bench <- as.Date(seq(as.Date("1999-01-01"),as.Date("2008-01-01"),by='month')) expect_equivalent(tbs, bench, info = info_msg) # retclass=POSIXct info_msg <- "test.tbs_199901_to_200801_by_month_POSIXct" tbs <- timeBasedSeq('199901/200801', retclass='POSIXct') bench <- seq(as.POSIXct("1999-01-01"),as.POSIXct("2008-01-01"),by='month') expect_equivalent(tbs, bench, info = info_msg) info_msg <- "test.tbs_199901_to_2008_by_month_POSIXct" tbs <- timeBasedSeq('199901/2008', retclass='POSIXct') bench <- as.POSIXct(seq(as.POSIXct("1999-01-01"),as.POSIXct("2008-12-01"),by='month')) expect_equivalent(tbs, bench, info = info_msg) info_msg <- "test.tbs_1999_to_200801_by_month_POSIXct" tbs <- timeBasedSeq('1999/200801', retclass='POSIXct') bench <- seq(as.POSIXct("1999-01-01"),as.POSIXct("2008-01-01"),by='month') expect_equivalent(tbs, bench, info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-timeBasedSeq.R
## ## Unit Test for timeSeries class from Rmetrics timeSeries package ## ## if (requireNamespace("timeSeries", quietly = TRUE)) { data(sample_matrix) ############################################################################### ############################################################################### # # Multivariate timeSeries tests # ############################################################################### ############################################################################### ############################################################################### # create timeSeries object from sample_matrix sample.timeSeries <- timeSeries::timeSeries(sample_matrix,charvec=as.Date(rownames(sample_matrix))) ############################################################################### ############################################################################### # create corresponding 'xts' object sample.xts <- as.xts(sample.timeSeries) ############################################################################### ############################################################################### # test subsetting functionality of xts info_msg <- "test.convert_timeSeries_to_xts" expect_identical(sample.xts,as.xts(sample.timeSeries), info = info_msg) info_msg <- "test.convert_timeSeries_to_xts_j1" expect_identical(sample.xts[,1],as.xts(sample.timeSeries)[,1], info = info_msg) info_msg <- "test.convert_timeSeries_to_xts_i1" expect_identical(sample.xts[1,],as.xts(sample.timeSeries)[1,], info = info_msg) info_msg <- "test.convert_timeSeries_to_xts_i1j1" expect_identical(sample.xts[1,1],as.xts(sample.timeSeries)[1,1], info = info_msg) # end subsetting functionality ############################################################################### ############################################################################### # test 'reclass' info_msg <- "test.timeSeries_reclass" expect_identical(sample.timeSeries,reclass(try.xts(sample.timeSeries)), info = info_msg) info_msg <- "test.timeSeries_reclass_subset_reclass_j1" expect_identical(sample.timeSeries[,1],reclass(try.xts(sample.timeSeries))[,1], info = info_msg) info_msg <- "test.timeSeries_reclass_subset_as.xts_j1" spl <- sample.timeSeries[,1:2] respl <- reclass(try.xts(sample.timeSeries)[,1:2]) # timeSeries fails to maintain @positions correctly if one column is selected expect_identical(spl,respl, info = info_msg) #expect_identical(1,1, info = info_msg) info_msg <- "test.timeSeries_reclass_subset_timeSeries_j1" spl <- sample.timeSeries[,1:2] respl <- reclass(try.xts(sample.timeSeries[,1:2])) # timeSeries fails to maintain @positions correctly if one column is selected expect_identical(spl,respl, info = info_msg) # expect_identical(1,1, info = info_msg) # end 'reclass' ############################################################################### ############################################################################### ############################################################################### # # Univariate timeSeries tests # ############################################################################### ############################################################################### ############################################################################### # create timeSeries object from sample_matrix sample.timeSeries.univariate <- timeSeries::timeSeries(sample_matrix[,1],charvec=as.Date(rownames(sample_matrix))) ############################################################################### ############################################################################### # create corresponding 'xts' object sample.xts.univariate <- as.xts(sample.timeSeries.univariate) ############################################################################### ############################################################################### # test subsetting functionality of xts info_msg <- "test.convert_timeSeries.univariate_to_xts" expect_identical(sample.xts.univariate,as.xts(sample.timeSeries.univariate), info = info_msg) info_msg <- "test.convert_timeSeries.univariate_to_xts_j1" expect_identical(sample.xts.univariate[,1],as.xts(sample.timeSeries.univariate)[,1], info = info_msg) info_msg <- "test.convert_timeSeries.univariate_to_xts_i1" expect_identical(sample.xts.univariate[1,],as.xts(sample.timeSeries.univariate)[1,], info = info_msg) info_msg <- "test.convert_timeSeries.univariate_to_xts_i1j1" expect_identical(sample.xts.univariate[1,1],as.xts(sample.timeSeries.univariate)[1,1], info = info_msg) # end subsetting functionality ############################################################################### } # requireNamespace
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-timeSeries.R
# ensure first group is included in output info_msg <- "test.to.frequency_includes_first_group" data(sample_matrix) x <- as.xts(sample_matrix) x$Volume <- 1 tf <- xts:::to.frequency(x, x$Volume, 90, name=NULL) tp <- .Call(xts:::C_toPeriod, x, c(0L, 90L, 180L), TRUE, 5L, FALSE, FALSE, c("Open", "High", "Low", "Close", "Volume")) expect_identical(tf, tp, info = info_msg) info_msg <- "test.to.period_custom_endpoints" data(sample_matrix) x <- as.xts(sample_matrix) ep <- endpoints(x, "months", 1) y1 <- to.period(x, "months", 1) y2 <- to.period(x, ep) expect_identical(y1, y2, info = info_msg) # period must be character or numeric expect_error(to.period(x, TRUE), info = "period must be character or numeric") # 'k' and 'indexAt' are ignored expect_warning(to.period(x, ep, k = 2), info = "'k' is ignored when endpoints are provided") expect_warning(to.period(x, ep, indexAt = ""), info = "'indexAt' is ignored when endpoints are provided")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-to.period.R
data(sample_matrix) sample.ts1 <- ts(sample_matrix,start=as.numeric(as.Date(rownames(sample_matrix)[1]))) sample.xts.ts1 <- as.xts(sample.ts1) info_msg <- "test.convert_ts_to_xts" expect_identical(sample.xts.ts1, as.xts(sample.ts1), info = info_msg) info_msg <- "test.convert_ts_to_xts_j1" expect_identical(sample.xts.ts1[,1], as.xts(sample.ts1)[,1], info = info_msg) info_msg <- "test.convert_ts_to_xts_i1" expect_identical(sample.xts.ts1[1,], as.xts(sample.ts1)[1,], info = info_msg) info_msg <- "test.convert_ts_to_xts_i1j1" expect_identical(sample.xts.ts1[1,1], as.xts(sample.ts1)[1,1], info = info_msg) info_msg <- "test.ts_reclass" expect_identical(sample.ts1, reclass(try.xts(sample.ts1)), info = info_msg) info_msg <- "test.ts_reclass_subset_reclass_j1" expect_identical(sample.ts1[,1], reclass(try.xts(sample.ts1))[,1], info = info_msg) info_msg <- "test.ts_reclass_subset_as.xts_j1" expect_identical(sample.ts1[,1], reclass(try.xts(sample.ts1)[,1]), info = info_msg) info_msg <- "test.ts_reclass_subset_ts_j1" expect_identical(sample.ts1[,1], reclass(try.xts(sample.ts1[,1])), info = info_msg) # quarterly series sample.ts4 <- ts(sample_matrix,start=1960,frequency=4) sample.xts.ts4 <- as.xts(sample.ts4) info_msg <- "test.convert_ts4_to_xts" expect_identical(sample.xts.ts4, as.xts(sample.ts4), info = info_msg) info_msg <- "test.convert_ts4_to_xts_j1" expect_identical(sample.xts.ts4[,1], as.xts(sample.ts4)[,1], info = info_msg) info_msg <- "test.convert_ts4_to_xts_i1" expect_identical(sample.xts.ts4[1,], as.xts(sample.ts4)[1,], info = info_msg) info_msg <- "test.convert_ts4_to_xts_i1j1" expect_identical(sample.xts.ts4[1,1], as.xts(sample.ts4)[1,1], info = info_msg) info_msg <- "test.ts4_reclass" expect_identical(sample.ts4, reclass(try.xts(sample.ts4)), info = info_msg) info_msg <- "test.ts4_reclass_subset_reclass_j1" expect_identical(sample.ts4[,1], reclass(try.xts(sample.ts4))[,1], info = info_msg) info_msg <- "test.ts4_reclass_subset_as.xts_j1" expect_identical(sample.ts4[,1], reclass(try.xts(sample.ts4)[,1]), info = info_msg) info_msg <- "test.ts4_reclass_subset_ts_j1" expect_identical(sample.ts4[,1], reclass(try.xts(sample.ts4[,1])), info = info_msg) # monthly series sample.ts12 <- ts(sample_matrix,start=1990,frequency=12) sample.xts.ts12 <- as.xts(sample.ts12) info_msg <- "test.convert_ts12_to_xts" expect_identical(sample.xts.ts12, as.xts(sample.ts12), info = info_msg) info_msg <- "test.convert_ts12_to_xts_j1" expect_identical(sample.xts.ts12[,1], as.xts(sample.ts12)[,1], info = info_msg) info_msg <- "test.convert_ts12_to_xts_i1" expect_identical(sample.xts.ts12[1,], as.xts(sample.ts12)[1,], info = info_msg) info_msg <- "test.convert_ts12_to_xts_i1j1" expect_identical(sample.xts.ts12[1,1], as.xts(sample.ts12)[1,1], info = info_msg) info_msg <- "test.ts12_reclass" expect_identical(sample.ts12, reclass(try.xts(sample.ts12)), info = info_msg) info_msg <- "test.ts12_reclass_subset_reclass_j1" expect_identical(sample.ts12[,1], reclass(try.xts(sample.ts12))[,1], info = info_msg) info_msg <- "test.ts12_reclass_subset_as.xts_j1" expect_identical(sample.ts12[,1], reclass(try.xts(sample.ts12)[,1]), info = info_msg) info_msg <- "test.ts12_reclass_subset_ts_j1" expect_identical(sample.ts12[,1], reclass(try.xts(sample.ts12[,1])), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-ts.R
# These tests check the timezone attribute is attached to the expected # component of the xts object. The xts constructors should no longer add # 'tzone' or '.indexTZ' attributes to the xts object itself. Only the index # should have a 'tzone' attribute. Construct xts objects using structure() to # test behavior when functions encounter xts objects created before 0.10-3. x <- structure(1:5, .Dim = c(5L, 1L), index = structure(1:5, tzone = "", tclass = c("POSIXct", "POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "UTC", tzone = "UTC", class = c("xts", "zoo")) info_msg <- "test.get_tzone" expect_identical(tzone(x), "", info = info_msg) info_msg <- "indexTZ(x) warns" expect_warning(indexTZ(x)) info_msg <- "indexTZ(x) <- warns" expect_warning(indexTZ(x) <- "GMT") info_msg <- "tzone(x) <- `foo` removes tzone and .indexTZ from xts object" y <- x tzone(y) <- "GMT" expect_identical(NULL, attr(y, "tzone"), info = info_msg) expect_identical(NULL, attr(y, ".indexTZ"), info = info_msg) info_msg <- "tzone(x) <- `foo` sets the tzone attribute on the index" y <- x tzone(y) <- "GMT" expect_identical("GMT", attr(attr(y, "index"), "tzone"), info = info_msg) expect_null(attr(y, ".indexTZ"), info = "tzone(x) <- `foo` removes .indexTZ attribute from xts object") info_msg <- "tzone(x) <- NULL sets the tzone attribute on the index to '' (empty string)" y <- x tzone(y) <- NULL expect_identical("", attr(attr(y, "index"), "tzone"), info = info_msg) info_msg <- "coredata(x) removes tzone and .indexTZ from xts object" y <- coredata(x) expect_identical(NULL, attr(y, "tzone"), info = info_msg) expect_identical(NULL, attr(y, ".indexTZ"), info = info_msg) info_msg <- "xtsAttributes(x) does not include tzone or .indexTZ" y <- xtsAttributes(x) expect_identical(NULL, y$tzone, info = info_msg) expect_identical(NULL, y$.indexTZ, info = info_msg) info_msg <- "xtsAttributes(x) <- 'foo' removes tzone and .indexTZ" y <- x xtsAttributes(y) <- xtsAttributes(x) expect_identical(NULL, attr(y, "tzone"), info = info_msg) expect_identical(NULL, attr(y, ".indexTZ"), info = info_msg) info_msg <- "tzone(x) <- `foo` always creates a character tzone" x <- "hello" tzone(x) <- 1 expect_identical(storage.mode(attr(x, "tzone")), "character", info = info_msg) info_msg <- "zero-width subset has the same tzone as the input" target <- "Ima/Tzone" x <- .xts(1:10, 1:10, tzone = target) y <- x[,0] expect_equal(target, tzone(y), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-tzone.R
# Tests for xts constructors ### NA in order.by {{{ # .xts() expect_error(.xts(1:3, c(1L, 2L, NA)), info = ".xts() order.by ends with NA_integer_") expect_error(.xts(1:3, c(NA, 2L, 3L)), info = ".xts() order.by starts with NA_integer_") expect_error(.xts(1:3, c(1L, NA, 3L)), info = ".xts() order.by contains NA_integer_") expect_error(.xts(1:3, c(1, 2, NA)), info = ".xts() order.by ends with NA_real_") expect_error(.xts(1:3, c(NA, 2, 3)), info = ".xts() order.by starts with NA_real_") expect_error(.xts(1:3, c(1, NA, 3)), info = ".xts() order.by contains NA_real_") expect_error(.xts(1:3, c(1, 2, NaN)), info = ".xts() order.by ends with NaN") expect_error(.xts(1:3, c(NaN, 2, 3)), info = ".xts() order.by starts with NaN") expect_error(.xts(1:3, c(1, NaN, 3)), info = ".xts() order.by contains NaN") expect_error(.xts(1:3, c(1, 2, Inf)), info = ".xts() order.by ends with Inf") expect_error(.xts(1:3, c(-Inf, 2, 3)), info = ".xts() order.by starts with -Inf") # xts() expect_error(xts(1:3, as.Date(c(1L, 2L, NA), origin = "1970-01-01")), info = "xts() order.by ends with NA_integer_") expect_error(xts(1:3, as.Date(c(NA, 2L, 3L), origin = "1970-01-01")), info = "xts() order.by starts with NA_integer_") expect_error(xts(1:3, as.Date(c(1L, NA, 3L), origin = "1970-01-01")), info = "xts() order.by contains NA_integer_") expect_error(xts(1:3, .POSIXct(c(1, 2, NA))), info = "xts() order.by ends with NA_real_") expect_error(xts(1:3, .POSIXct(c(NA, 2, 3))), info = "xts() order.by starts with NA_real_") expect_error(xts(1:3, .POSIXct(c(1, NA, 3))), info = "xts() order.by contains NA_real_") expect_error(xts(1:3, .POSIXct(c(1, 2, NaN))), info = "xts() order.by ends with NaN") expect_error(xts(1:3, .POSIXct(c(NaN, 2, 3))), info = "xts() order.by starts with NaN") expect_error(xts(1:3, .POSIXct(c(1, NaN, 3))), info = "xts() order.by contains NaN") expect_error(xts(1:3, .POSIXct(c(1, 2, Inf))), info = "xts() order.by ends with Inf") expect_error(xts(1:3, .POSIXct(c(-Inf, 2, 3))), info = "xts() order.by starts with -Inf") ### }}} # Test that only first tzone element is stored for POSIXlt tz <- "America/Chicago" i <- as.POSIXlt("2018-01-01", tz = tz) y <- xts(1, i) expect_identical(tz, tzone(y), info = "xts() only uses the first element of tzone for POSIXlt order.by") ### constructors add tzone and tclass to the index by default x <- xts() expect_true(!is.null(attr(attr(x, "index"), "tclass")), info = "xts() with no args adds tclass to the index") expect_true(!is.null(attr(attr(x, "index"), "tzone")), info = "xts() with no args adds tzone to the index") x <- .xts(, .POSIXct(integer())) expect_true(!is.null(attr(attr(x, "index"), "tclass")), info = ".xts() with no args adds tclass to the index") expect_true(!is.null(attr(attr(x, "index"), "tzone")), info = ".xts() with no args adds tzone to the index") ### constructor defaults don't add index attributes to the xts object x <- xts(1, as.Date("2018-05-02")) expect_null(attr(x, "tclass"), info = "xts(<defaults>) doesn't add tclass to xts object") expect_null(attr(x, ".indexCLASS"), info = "xts(<defaults>) doesn't add .indexCLASS to xts object") y <- .xts(1, 1) expect_null(attr(y, "tclass"), info = ".xts(<defaults>) doesn't add .indexCLASS to xts object") expect_null(attr(y, ".indexCLASS"), info = ".xts(<defaults>) doesn't add .indexCLASS to xts object") x <- xts(1, as.Date("2018-05-02")) expect_null(attr(x, "tzone"), info = "xts(<defaults>) doesn't add tzone to xts object") expect_null(attr(x, ".indexTZ"), info = "xts(<defaults>) doesn't add .indexTZ to xts object") y <- .xts(1, 1) expect_null(attr(y, "tzone"), info = ".xts(<defaults>) doesn't add tzone to xts object") expect_null(attr(y, ".indexTZ"), info = ".xts(<defaults>) doesn't add .indexTZ to xts object") x <- xts(1, as.Date("2018-05-02")) expect_null(attr(x, "tformat"), info = "xts(<defaults>) doesn't add tformat to xts object") expect_null(attr(x, ".indexFORMAT"), info = "xts(<defaults>) doesn't add .indexFORMAT to xts object") y <- .xts(1, 1) expect_null(attr(y, "tformat"), info = ".xts(<defaults>) doesn't add tformat to xts object") expect_null(attr(y, ".indexFORMAT"), info = ".xts(<defaults>) doesn't add .indexFORMAT to xts object") ### constructor with index attributes specified doesn't add them to the xts object create_msg <- function(func, attrib) { paste0(func, "(..., ", attrib, " = 'foo' doesn't add ", attrib, " to the xts object") } suppressWarnings({ x <- xts(1, Sys.time(), .indexCLASS = "yearmon") y <- xts(1, Sys.time(), .indexFORMAT = "%Y") z <- xts(1, Sys.time(), .indexTZ = "UTC") }) expect_null(attr(x, ".indexCLASS"), info = create_msg("xts", ".indexCLASS")) expect_null(attr(y, ".indexFORMAT"), info = create_msg("xts", ".indexFORMAT")) expect_null(attr(z, ".indexTZ"), info = create_msg("xts", ".indexTZ")) suppressWarnings({ x <- .xts(1, Sys.time(), .indexCLASS = "yearmon") y <- .xts(1, Sys.time(), .indexFORMAT = "%Y") z <- .xts(1, Sys.time(), .indexTZ = "UTC") }) expect_null(attr(x, ".indexCLASS"), info = create_msg(".xts", ".indexCLASS")) expect_null(attr(y, ".indexFORMAT"), info = create_msg(".xts", ".indexFORMAT")) expect_null(attr(z, ".indexTZ"), info = create_msg(".xts", ".indexTZ")) x <- xts(1, Sys.time(), tclass = "Date") y <- xts(1, Sys.time(), tformat = "%Y-%m-%d %H:%M") z <- xts(1, Sys.time(), tzone = "UTC") expect_null(attr(x, "tclass"), info = create_msg("xts", "tclass")) expect_null(attr(y, "tformat"), info = create_msg("xts", "tformat")) expect_null(attr(z, "tzone"), info = create_msg("xts", "tzone")) x <- .xts(1, Sys.time(), tclass = "Date") y <- .xts(1, Sys.time(), tformat = "%Y-%m-%d %H:%M") z <- .xts(1, Sys.time(), tzone = "UTC") expect_null(attr(x, "tclass"), info = create_msg(".xts", "tclass")) expect_null(attr(y, "tformat"), info = create_msg(".xts", "tformat")) expect_null(attr(z, "tzone"), info = create_msg(".xts", "tzone")) # These error due to `missing("tclass")` instead of `!hasArg("tclass")` # missing() expects an argument symbol, not a character string. The error is # not caught in expect_warning() as of tinytest_1.3.1 suppressWarnings(xts(1, as.Date("2018-05-02"), .indexCLASS = "Date")) suppressWarnings(xts(1, as.Date("2018-05-02"), .indexFORMAT = "%Y")) suppressWarnings(.xts(1, 1, .indexCLASS = "Date")) suppressWarnings(.xts(1, 1, .indexFORMAT = "%Y")) ### warn if deprecated arguments passed to constructor deprecated_warns <- list(iclass = "'.indexCLASS' is deprecated.*use tclass instead", izone = "'.indexTZ' is deprecated.*use tzone instead", iformat = "'.indexFORMAT' is deprecated.*use tformat instead") expect_warning(x <- xts(1, as.Date("2018-05-02"), .indexCLASS = "Date"), pattern = deprecated_warns$iclass, info = "xts() warns when .indexCLASS argument is provided") expect_warning(x <- .xts(1, as.Date("2018-05-02"), .indexCLASS = "Date"), pattern = deprecated_warns$iclass, info = ".xts() warns when .indexCLASS argument is provided") expect_warning(x <- xts(1, as.Date("2018-05-02"), .indexTZ = "UTC"), pattern = deprecated_warns$izone, info = "xts() warns when .indexTZ argument is provided") expect_warning(x <- .xts(1, as.Date("2018-05-02"), .indexTZ = "UTC"), pattern = deprecated_warns$izone, info = ".xts() warns when .indexTZ argument is provided") expect_warning(x <- xts(1, as.Date("2018-05-02"), .indexFORMAT = "%Y"), pattern = deprecated_warns$iformat, info = "xts() warns when .indexFORMAT is provided") expect_warning(x <- .xts(1, as.Date("2018-05-02"), .indexFORMAT = "%Y"), pattern = deprecated_warns$iformat, info = ".xts() warns when .indexFORMAT is provided") ### constructors add tformat to the index when it's specified tf <- "%m/%d/%Y" x <- xts(1:3, .Date(1:3), tformat = tf) y <- .xts(1:3, .Date(1:3), tformat = tf) expect_identical(tf, attr(attr(x, "index"), "tformat"), info = "xts(..., tformat = 'foo') adds tformat to index") expect_identical(tf, attr(attr(y, "index"), "tformat"), info = ".xts(..., tformat = 'foo') adds tformat to index") ### dimnames come through '...' x <- xts(1:5, .Date(1:5), dimnames = list(NULL, "x")) y <- .xts(1:5, 1:5, dimnames = list(NULL, "x")) expect_equal(colnames(x), colnames(y), info = "xts() and .xts() apply dimnames passed via '...'") x <- xts(1:5, .Date(1:5), dimnames = list(1:5, "x")) y <- .xts(1:5, 1:5, dimnames = list(1:5, "x")) expect_null(rownames(x), info = "xts() doesn't set rownames when dimnames passed via '...'") expect_null(rownames(y), info = ".xts() doesn't set rownames when dimnames passed via '...'") m <- matrix(1, dimnames = list("a", "b")) x <- .xts(m, 1) expect_null(rownames(x), info = ".xts() on a matrix with rownames does not have rownames") # test..xts_ctor_warns_if_index_tclass_not_NULL_or_POSIXct <- function() { # DEACTIVATED("Warning causes errors in dependencies") # # idx <- 1:3 # x <- .xts(1:3, idx) # no error, NULL # idx <- .POSIXct(idx) # x <- .xts(1:3, idx) # no error, POSIXct # # idx <- structure(1:3, tclass = "Date", tzone = "UTC") # expect_warning(.xts(1:3, idx), msg = "tclass = Date") # idx <- structure(idx, tclass = "yearmon", tzone = "UTC") # expect_warning(.xts(1:3, idx), msg = "tclass = yearmon") # idx <- structure(idx, tclass = "timeDate", tzone = "UTC") # expect_warning(.xts(1:3, idx), msg = "tclass = timeDate") # } ### xts() index attribute precedence should be: ### 1. .index* value (e.g. .indexTZ) # backward compatibility ### 2. t* value (e.g. tzone) # current function to override index attribute ### 3. attribute on order.by # overridden by either 2 above target_index <- structure(Sys.time(), tzone = "UTC", tclass = "yearmon", tformat = "%Y-%m-%d") suppressWarnings({ x <- xts(1, target_index, .indexCLASS = "Date", tclass = "yearqtr") y <- xts(1, target_index, .indexFORMAT = "%Y-%b", tformat = "%Y-%m") z <- xts(1, target_index, .indexTZ = "Asia/Tokyo", tzone = "Europe/London") }) expect_identical(tclass(x), "Date", info = "xts() .indexCLASS takes precedence over tclass") expect_identical(tformat(y), "%Y-%b", info = "xts() .indexFORMAT takes precedence over tformat") expect_identical(tzone(z), "Asia/Tokyo", info = "xts() .indexTZ takes precedence over tzone") x <- xts(1, target_index, tclass = "yearqtr") y <- xts(1, target_index, tformat = "%Y-%m") z <- xts(1, target_index, tzone = "Europe/London") expect_identical(tclass(x), "yearqtr", info = "xts() tclass takes precedence over index tclass") expect_identical(tformat(y), "%Y-%m", info = "xts() tformat takes precedence over index tformat") expect_identical(tzone(z), "Europe/London", info = "xts() tzone takes precedence over index tzone") x <- xts(1, target_index) y <- xts(1, target_index) z <- xts(1, target_index) expect_identical(tclass(x), attr(target_index, "tclass"), info = "xts() uses index tclass") expect_identical(tformat(y), attr(target_index, "tformat"), info = "xts() uses index tformat") expect_identical(tzone(z), attr(target_index, "tzone"), info = "xts() uses index tzone") ### .xts() index attribute precedence is similar. But we cannot override tclass ### because it's a formal argument with a specific default. Historically .xts() ### has always set the tclass to POSIXct by default, whether or not the 'index' ### argument already had a tclass attribute. target_index <- structure(as.POSIXlt(Sys.time()), tzone = "UTC", tclass = "yearmon", tformat = "%Y-%m-%d") suppressWarnings({ x <- .xts(1, target_index, .indexCLASS = "Date", tclass = "yearqtr") y <- .xts(1, target_index, .indexFORMAT = "%Y-%b", tformat = "%Y-%m") z <- .xts(1, target_index, .indexTZ = "Asia/Tokyo", tzone = "Europe/London") }) expect_identical(tclass(x), "Date", info = ".xts() .indexCLASS takes precedence over tclass") expect_identical(tformat(y), "%Y-%b", info = ".xts() .indexFORMAT takes precedence over tformat") expect_identical(tzone(z), "Asia/Tokyo", info = ".xts() .indexTZ takes precedence over tzone") x <- .xts(1, target_index, tclass = "yearqtr") y <- .xts(1, target_index, tformat = "%Y-%m") z <- .xts(1, target_index, tzone = "Europe/London") expect_identical(tclass(x), "yearqtr", info = ".xts() tclass takes precedence over index tclass") expect_identical(tformat(y), "%Y-%m", info = ".xts() tformat takes precedence over index tformat") expect_identical(tzone(z), "Europe/London", info = ".xts() tzone takes precedence over index tzone") x <- .xts(1, target_index) y <- .xts(1, target_index) z <- .xts(1, target_index) # NOTE: as of 0.10-0, .xts() sets tclass on the index to "POSIXct" by default. # It does not keep the index argument's tclass if it has one. So overriding # the default with the index's tclass attribute is a breaking change. expect_identical(tclass(x), c("POSIXct", "POSIXt"), info = ".xts() *ignores* index tclass (unlike xts())") # tformat and tzone are handled the same as in xts() expect_identical(tformat(y), attr(target_index, "tformat"), info = ".xts() uses index tformat") expect_identical(tzone(z), attr(target_index, "tzone"), info = ".xts() uses index tzone") suppressWarnings({ x <- xts(1, Sys.Date(), tformat = "%Y", .indexCLASS = "Date", .indexTZ = "UTC", user = "attribute", hello = "world", dimnames = list(NULL, "x")) y <- .xts(1, 1, tformat = "%Y", .indexCLASS = "Date", .indexTZ = "UTC", user = "attribute", hello = "world", dimnames = list(NULL, "x")) }) info_msg <- "xts() adds user attributes" expect_null(attr(x, "tformat"), info = info_msg) expect_null(attr(x, "tclass"), info = info_msg) expect_null(attr(x, "tzone"), info = info_msg) expect_null(attr(x, ".indexCLASS"), info = info_msg) expect_null(attr(x, ".indexTZ"), info = info_msg) expect_identical("attribute", attr(x, "user"), info = info_msg) expect_identical("world", attr(x, "hello"), info = info_msg) expect_identical("x", colnames(x), info = info_msg) info_msg <- ".xts() adds user attributes" expect_null(attr(y, "tformat"), info = info_msg) expect_null(attr(y, "tclass"), info = info_msg) expect_null(attr(y, "tzone"), info = info_msg) expect_null(attr(y, ".indexCLASS"), info = info_msg) expect_null(attr(y, ".indexTZ"), info = info_msg) expect_identical("attribute", attr(y, "user"), info = info_msg) expect_identical("world", attr(y, "hello"), info = info_msg) expect_identical("x", colnames(y), info = info_msg) ### constructors should not warn for Date, yearmon, yearqtr, chron::chron, chron::dates ### and should set tzone to UTC for any UTC-equivalent tzone create_msg <- function(klass, tz, warns = TRUE) { warn_part <- if(warns) "warns" else "doesn't warn" sprintf("xts(1, %s(...), tzone = '%s') %s", klass, tz, warn_part) } create_msg. <- function(klass, tz, warns = TRUE) { paste0(".", create_msg(klass, tz, warns)) } ym <- as.yearmon(Sys.Date()) yq <- as.yearqtr(Sys.Date()) for(tz in c("UTC", "GMT", "Etc/UTC", "Etc/GMT", "GMT-0", "GMT+0", "GMT0")) { # xts() x <- y <- z <- NULL expect_silent(x <- xts(1, .Date(1), tzone = tz), info = create_msg("Date()", tz, FALSE)) expect_silent(y <- xts(1, ym, tzone = tz), info = create_msg("yearmon", tz, FALSE)) expect_silent(z <- xts(1, yq, tzone = tz), info = create_msg("yearqtr", tz, FALSE)) expect_identical(tzone(x), "UTC", info = "xts() UTC-equivalent tzone is set to UTC (Date)") expect_identical(tzone(y), "UTC", info = "xts() UTC-equivalent tzone is set to UTC (yearmon)") expect_identical(tzone(z), "UTC", info = "xts() UTC-equivalent tzone is set to UTC (yearqtr)") # .xts() x <- y <- z <- NULL expect_silent(x <- .xts(1, .Date(1), tzone = tz), info = create_msg.("Date", tz, FALSE)) expect_silent(y <- .xts(1, ym, tzone = tz), info = create_msg.("yearmon", tz, FALSE)) expect_silent(z <- .xts(1, yq, tzone = tz), info = create_msg.("yearqtr", tz, FALSE)) expect_identical(tzone(x), "UTC", info = ".xts() UTC-equivalent tzone is set to UTC (Date)") expect_identical(tzone(y), "UTC", info = ".xts() UTC-equivalent tzone is set to UTC (yearmon)") expect_identical(tzone(z), "UTC", info = ".xts() UTC-equivalent tzone is set to UTC (yearqtr)") if(requireNamespace("chron", quietly = TRUE)) { x <- y <- NULL expect_silent(x <- xts(1, chron::chron(1, 1), tzone = tz), info = create_msg("chron", tz, FALSE)) expect_silent(y <- xts(1, chron::dates(1), tzone = tz), info = create_msg("dates", tz, FALSE)) expect_identical(tzone(x), "UTC", info = "xts() UTC-equivalent tzone is set to UTC (chron)") expect_identical(tzone(y), "UTC", info = ".xts() UTC-equivalent tzone is set to UTC (dates)") x <- y <- NULL expect_silent(x <- .xts(1, chron::chron(1, 1), tzone = tz), info = create_msg.("chron", tz, FALSE)) expect_silent(y <- .xts(1, chron::dates(1), tzone = tz), info = create_msg.("dates", tz, FALSE)) expect_identical(tzone(x), "UTC", info = "xts() UTC-equivalent tzone is set to UTC (chron)") expect_identical(tzone(y), "UTC", info = ".xts() UTC-equivalent tzone is set to UTC (dates)") } } ### constructors warn and ignore non-UTC tzone for index/order.by classes without timezones tz <- "America/Chicago" warn_pattern <- "tzone.*setting ignored for.*indexes" # xts() x <- y <- z <- NULL expect_warning(x <- xts(1, .Date(1), tzone = tz), pattern = warn_pattern, info = create_msg("Date", tz, TRUE)) expect_warning(y <- xts(1, ym, tzone = tz), pattern = warn_pattern, info = create_msg("yearmon", tz, TRUE)) expect_warning(z <- xts(1, yq, tzone = tz), pattern = warn_pattern, info = create_msg("yearqtr", tz, TRUE)) expect_identical(tzone(x), "UTC", info = "xts() non-UTC tzone is set to UTC (Date)") expect_identical(tzone(y), "UTC", info = "xts() non-UTC tzone is set to UTC (yearmon)") expect_identical(tzone(z), "UTC", info = "xts() non-UTC tzone is set to UTC (yearqtr)") # .xts() x <- y <- z <- NULL expect_warning(x <- .xts(1, .Date(1), tzone = tz), pattern = warn_pattern, info = create_msg("yearqtr", tz, TRUE)) expect_warning(y <- .xts(1, ym, tzone = tz), pattern = warn_pattern, info = create_msg("Date", tz, TRUE)) expect_warning(z <- .xts(1, yq, tzone = tz), pattern = warn_pattern, info = create_msg("yearmon", tz, TRUE)) expect_identical(tzone(x), "UTC", info = ".xts() non-UTC tzone is set to UTC (Date)") expect_identical(tzone(y), "UTC", info = ".xts() non-UTC tzone is set to UTC (yearmon)") expect_identical(tzone(z), "UTC", info = ".xts() non-UTC tzone is set to UTC (yearqtr)") if(requireNamespace("chron", quietly = TRUE)) { x <- y <- NULL expect_warning(x <- xts(1, chron::chron(1, 1), tzone = tz), pattern = warn_pattern, info = create_msg("chron", tz, TRUE)) expect_warning(y <- xts(1, chron::dates(1), tzone = tz), pattern = warn_pattern, info = create_msg("dates", tz, TRUE)) expect_identical(tzone(x), "UTC", info = "xts() non-UTC tzone is set to UTC (chron)") expect_identical(tzone(y), "UTC", info = "xts() non-UTC tzone is set to UTC (dates)") x <- y <- NULL expect_warning(x <- .xts(1, chron::chron(1, 1), tzone = tz), pattern = warn_pattern, info = create_msg.("chron", tz, TRUE)) expect_warning(y <- .xts(1, chron::dates(1), tzone = tz), pattern = warn_pattern, info = create_msg.("dates", tz, TRUE)) expect_identical(tzone(x), "UTC", info = ".xts() non-UTC tzone is set to UTC (chron)") expect_identical(tzone(y), "UTC", info = ".xts() non-UTC tzone is set to UTC (dates)") } ### lists and zero-row data.frames msg <- "cannot convert lists to xts objects" expect_error(xts(list(1, 2), .Date(1:2)), msg, info = msg) #expect_error(.xts(list(1, 2), 1:2), msg, info = msg) zero_row_df <- data.frame(date = .Date(numeric(0)), x = numeric(0), y = numeric(0)) zero_row_xts <- xts(zero_row_df[, -1], zero_row_df[, 1]) expect_identical(names(zero_row_xts), names(zero_row_df)[-1], info = "xts() keeps names for zero-row data.frame") expect_equal(.Date(numeric(0)), index(zero_row_xts), info = "xts() has zero-length Date index for zero-row data.frame with Date column") zero_row_xts. <- .xts(zero_row_df[, -1], zero_row_df[, 1]) expect_identical(names(zero_row_xts.), names(zero_row_df)[-1], info = ".xts() keeps names for zero-row data.frame") expect_equal(.Date(numeric(0)), index(zero_row_xts.), info = ".xts() has zero-length Date index for zero-row data.frame with Date column")
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-xts.R
# unit tests for the following 'xts' methods: # rbind # cbind # info_msg <- "test.rbind_zero_length_non_zero_length_POSIXct_errors" xpz <- xts( , as.POSIXct("2017-01-01")) xp1 <- xts(1, as.POSIXct("2017-01-02")) zpz <- as.zoo(xpz) zp1 <- as.zoo(xp1) zpe <- tryCatch(rbind(zpz, zp1), error = identity) xpe <- tryCatch(rbind(xpz, xp1), error = identity) expect_identical(zpe$message, xpe$message, info = info_msg) info_msg <- "test.rbind_zero_length_non_zero_length_Date_errors" xpz <- xts( , as.Date("2017-01-01")) xp1 <- xts(1, as.Date("2017-01-02")) zpz <- as.zoo(xpz) zp1 <- as.zoo(xp1) zpe <- tryCatch(rbind(zpz, zp1), error = identity) xpe <- tryCatch(rbind(xpz, xp1), error = identity) expect_identical(zpe$message, xpe$message, info = info_msg) info_msg <- "test.rbind_no_dim_does_not_error" d <- rep(0.1, 2) i <- rep(581910048, 2) xts_no_dim <- structure(d[1], class = c("xts", "zoo"), index = structure(i[1], tzone = "UTC", tclass = "Date")) xts_out <- structure(d, class = c("xts", "zoo"), .Dim = 2:1, index = structure(i, tzone = "UTC", tclass = "Date")) xts_rbind <- rbind(xts_no_dim, xts_no_dim) expect_identical(xts_out, xts_rbind, info = info_msg) # Test that as.Date.numeric() works at the top level (via zoo::as.Date()), # and for functions defined in the xts namespace even if xts::as.Date.numeric() # is not formally registered as an S3 method. info_msg <- "test.as.Date.numeric" # Define function that calls as.Date.numeric() ... f <- function(d) { as.Date(d) } # ... in xts' namespace environment(f) <- as.environment("package:xts") dd <- as.Date("2017-12-13") dn <- unclass(dd) expect_identical(dd, as.Date(dn), info = info_msg) # via zoo::as.Date() expect_identical(dd, f(dn), info = info_msg) # .subset.xts # window.xts # .toPOSIXct (indirectly) info_msg <- "test.window" # window function for xts series, use basic logic for testing & debugging # null start and end not supported window_dbg <- function(x, index. = index(x), start, end) { start <- xts:::.toPOSIXct(start, tzone(x)) end <- xts:::.toPOSIXct(end, tzone(x)) index. <- as.POSIXct(index., tz=tzone(x)) all.indexes <- .index(x) in.index <- all.indexes %in% as.numeric(index.) matches <- (in.index & all.indexes >= start & all.indexes <= end) x[matches,] } DAY = 24*3600 base <- as.POSIXct("2000-12-31") dts <- base + c(1:10, 12:15, 17:20)*DAY x <- xts(1:length(dts), dts) # Range over gap start <- base + 11*DAY end <- base + 16*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- range over gap")) # Range over one day start <- base + 12*DAY end <- base + 12*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- range over one day")) # Empty Range over one day start <- base + 11*DAY end <- base + 11*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- empty Range over one day")) # Range containing all dates start <- base end <- base + 21*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- range containing all dates")) # Range past end start <- base + 16*DAY end <- base + 30*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- range past end")) # Range before begin start <- base end <- base + 3*DAY bin <- window(x, start = start, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- range before begin")) # Test just start, end = NULL start <- base + 13 * DAY end <- base + 30*DAY bin <- window(x, start = start) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just start, end = NULL")) # Test just start, end = NULL, empty range start <- base + 25 * DAY end <- base + 30*DAY bin <- window(x, start = start) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just start, end = NULL, empty range")) # Test just end, start = NULL end <- base + 13 * DAY start <- base bin <- window(x, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just end, start = NULL")) # Test just end, start = NULL, empty range end <- base start <- base bin <- window(x, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just end, start = NULL, empty range")) # Test end = NULL, start = NULL start <- base end <- base + 30*DAY bin <- window(x) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- end = NULL, start = NULL")) # Test just start, end = NA start <- base + 13 * DAY end <- base + 30*DAY bin <- window(x, start = start, end = NA) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just start, end = NA")) # Test just start, end = NA, empty range start <- base + 25 * DAY end <- base + 30*DAY bin <- window(x, start = start, end = NA) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just start, end = NA, empty range")) # Test just end, start = NA end <- base + 13 * DAY start <- base bin <- window(x, start = NA, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just end, start = NA")) # Test just end, start = NA, empty range end <- base start <- base bin <- window(x, start = NA, end = end) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- just end, start = NA, empty range")) # Test end = NA, start = NA start <- base end <- base + 30*DAY bin <- window(x, start = NA, end = NA) reg <- window_dbg(x, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- end = NA, start = NA")) ####################################### # Test for index. parameter start <- base end <- base + 30*DAY idx = index(x)[c(2,4,6)] bin <- window(x, index. = idx) reg <- window_dbg(x, index. = idx, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- index. parameter provided")) # Test index. outside range of dates in xts series start <- base end <- base + 30*DAY idx = c(start, index(x)[c(2,4,6)], end) bin <- window(x, index. = idx) reg <- window_dbg(x, index. = idx, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- index. outside range of dates in xts series")) # Test NA in index start <- base end <- base + 30*DAY idx = c(start, index(x)[c(2,4,6)], end, NA) bin <- window(x, index. = idx) reg <- window_dbg(x, index. = idx, start = start, end = end) expect_identical(bin, reg, info = paste(info_msg, "- NA in index ")) # Next 3 adapted from window.zoo example # Test basic window.zoo example x.date <- as.Date(paste(2003, rep(1:4, 4:1), seq(1,19,2), sep = "-")) x <- xts(matrix(1:20, ncol = 2), x.date) bin <- window(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) reg <- window_dbg(x, start = as.Date("2003-02-01"), end = as.Date("2003-03-01")) expect_identical(bin, reg, info = paste(info_msg, "- basic window.zoo example")) # Test index + start bin <- window(x, index. = x.date[1:6], start = as.Date("2003-02-01")) reg <- window_dbg(x, index. = x.date[1:6], start = as.Date("2003-02-01"), end = as.Date("2004-01-01")) expect_identical(bin, reg, info = paste(info_msg, "- index + start")) # Test just index bin <- window(x, index. = x.date[c(4, 8, 10)]) reg <- window_dbg(x, index. = x.date[c(4, 8, 10)], start = as.Date("2003-01-01"), end = as.Date("2004-01-01")) expect_identical(bin, reg, info = paste(info_msg, "- just index")) # Test decreasing index bin <- window(x, index. = x.date[c(10, 8, 4)]) reg <- window_dbg(x, index. = x.date[c(10, 8, 4)], start = as.Date("2003-01-01"), end = as.Date("2004-01-01")) expect_identical(bin, reg, info = paste(info_msg, "- decreasing index")) # Test index parameter with repeated dates in xts series idx <- sort(rep(1:5, 5)) x <- xts(1:length(idx), as.Date("1999-12-31")+idx) bin <- window(x, index. = as.Date("1999-12-31")+c(1,3,5)) reg <- window_dbg(x, index. = as.Date("1999-12-31")+c(1,3,5), start = as.Date("2000-01-01"), end = as.Date("2000-01-05")) expect_identical(bin, reg, info = paste(info_msg, "- index parameter with repeated dates in xts series")) expect_true(nrow(bin) == 3*5, info = paste(info_msg, "- index parameter with repeated dates in xts series")) # Test performance difference DAY = 24*3600 base <- as.POSIXct("2000-12-31") dts <- base + c(1:10, 12:15, 17:20)*DAY x <- xts(1:length(dts), dts) start <- base + 14*DAY end <- base + 14*DAY #cat("\n") #print("performance:") #print("binary search") #print(system.time(replicate(1000, window(x, start = start, end = end)))) # Binary search is about 2x faster than regular #print("regular search") #print(system.time(replicate(1000, window_dbg(x, start = start, end = end)))) # test subset.xts for date subsetting by row info_msg <- "test.subset_i_datetime_or_character" base <- as.POSIXct("2000-12-31") dts <- base + c(1:10, 12:15, 17:20) * 24L * 3600L x <- xts(seq_along(dts), dts) # Note that "2001-01-11" is not in the series. Skipped by convention. d <- c("2001-01-10", "2001-01-11", "2001-01-12", "2001-01-13") for (type in c("double", "integer")) { storage.mode(.index(x)) <- type # Test scalar msg <- paste0(info_msg, " scalar, ", type, " index") bin <- window(x, start = d[1], end = d[1]) expect_identical(bin, x[d[1], ], info = paste("character", msg)) expect_identical(bin, x[I(d[1]), ], info = paste("as-is character", msg)) expect_identical(bin, x[as.POSIXct(d[1]), ], info = paste("POSIXct", msg)) expect_identical(bin, x[as.Date(d[1]), ], info = paste("Date", msg)) # Test vector msg <- paste0(info_msg, " vector, ", type, " index") bin <- window(x, start = d[1], end = d[length(d)]) expect_identical(bin, x[d, ], info = paste("character", msg)) expect_identical(bin, x[I(d), ], info = paste("as-is character", msg)) expect_identical(bin, x[as.POSIXct(d), ], info = paste("POSIXct", msg)) expect_identical(bin, x[as.Date(d), ], info = paste("Date", msg)) # Test character dates, and single column selection y <- xts(rep(2, length(dts)), dts) z <- xts(rep(3, length(dts)), dts) x2 <- cbind(y, x, z) sub <- x2[d, 2] # Note that "2001-01-11" is not in the series. Skipped by convention. bin <- window(x, start = d[1], end = d[length(d)]) expect_equal(nrow(sub), nrow(bin), info = paste(info_msg, "- character dates, and single column selection")) expect_true(all(sub == bin), info = paste(info_msg, "- character dates, and single column selection")) } info_msg <- "test.subset_i_ISO8601" x <- xts(1:1000, as.Date("2000-01-01")+1:1000) for (type in c("double", "integer")) { storage.mode(.index(x)) <- type # Test Date Ranges sub <- x['200001'] # January 2000 bin <- window(x, start = "2000-01-01", end = "2000-01-31") expect_identical(bin, sub, info = paste(info_msg, ", i = 2000-01")) # Test Date Ranges 2 sub <- x['1999/2000'] # All of 2000 (note there is no need to use the exact start) bin <- window(x, start = "2000-01-01", end = "2000-12-31") expect_identical(bin, sub, info = paste(info_msg, ", i = 1999/2000")) # Test Date Ranges 3 sub <- x['1999/200001'] # January 2000 bin <- window(x, start = "2000-01-01", end = "2000-01-31") expect_identical(bin, sub, info = paste(info_msg, ", i= 1999/2000-01")) }
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-xts.methods.R
#sample.zoo <- #structure(c(43.46, 43.3, 43.95, 43.89, 44.01, 43.96, 44.71, 45.02, #45.35, 45.09), .Names = c("264", "263", "262", "261", "260", #"259", "258", "257", "256", "255"), index = structure(c(13516, #13517, 13518, 13521, 13522, 13523, 13524, 13525, 13529, 13530 #), class = "Date"), class = "zoo") # #sample.xts <- #structure(c(43.46, 43.3, 43.95, 43.89, 44.01, 43.96, 44.71, 45.02, #45.35, 45.09), index = structure(c(13516, 13517, 13518, 13521, #13522, 13523, 13524, 13525, 13529, 13530), class = "Date"), class = c("xts", #"zoo"), .CLASS = "zoo", .Dim = c(10L, 1L), .Dimnames = list(c("264", #"263", "262", "261", "260", "259", "258", "257", "256", "255" #), NULL), .ROWNAMES = c("264","263","262", "261", "260", "259", #"258", "257", "256", "255")) # data(sample_matrix) sample.zoo <- zoo(sample_matrix, as.Date(rownames(sample_matrix))) sample.xts <- as.xts(sample.zoo) info_msg <- "test.convert_zoo_to_xts" expect_identical(sample.xts, as.xts(sample.zoo), info = info_msg) info_msg <- "test.convert_zoo_to_xts_j1" expect_identical(sample.xts[,1], as.xts(sample.zoo)[,1], info = info_msg) info_msg <- "test.convert_zoo_to_xts_i1" expect_identical(sample.xts[1,], as.xts(sample.zoo)[1,], info = info_msg) info_msg <- "test.convert_zoo_to_xts_i1j1" expect_identical(sample.xts[1,1], as.xts(sample.zoo)[1,1], info = info_msg) # test.zoo_reclass <- function() { # DEACTIVATED("rownames are not kept yet in current xts-dev") # expect_identical(sample.zoo,reclass(try.xts(sample.zoo)), info = info_msg) # } # test.zoo_reclass_subset_reclass_j1 <- function() { # DEACTIVATED("rownames are not kept yet in current xts-dev") # expect_identical(sample.zoo[,1],reclass(try.xts(sample.zoo))[,1], info = info_msg) # } info_msg <- "test.zoo_reclass_subset_as.xts_j1" expect_identical(sample.zoo[,1], reclass(try.xts(sample.zoo)[,1]), info = info_msg) info_msg <- "test.zoo_reclass_subset_zoo_j1" expect_identical(sample.zoo[,1], reclass(try.xts(sample.zoo[,1])), info = info_msg)
/scratch/gouwar.j/cran-all/cranData/xts/inst/tinytest/test-zoo.R
#' @importFrom dplyr all_of select mutate group_by summarise ungroup pull sym bind_rows bind_cols #' @importFrom magrittr %>% #' @importFrom plm pdata.frame index #' xtbetween <- function(data, variable = NULL, id = NULL, t = NULL, na.rm = FALSE) { # Check if data is a data.frame if (!is.data.frame(data)) { stop("data must be a data.frame object...") } # Check if id and t are provided if data is not a pdata.frame object if (any(is.null(id), is.null(t)) & !"pdata.frame" %in% class(data)) { stop("if data is not a pdata.frame object, id and t must be provided") } # If data is a pdata.frame object and id or t is missing, use pdata.frame index if ("pdata.frame" %in% class(data) & any(is.null(id), is.null(t))) { data$id <- plm::index(data)[1] %>% pull() data$t <- plm::index(data)[2] %>% pull() id <- "id" t <- "t" } # If variables are not specified, use all numeric variables in the data idt <- c(id, t) data_ <- as.data.frame(data) %>% dplyr::select(dplyr::all_of(idt), dplyr::all_of(variable)) data %>% dplyr::select(all_of(idt), all_of(variable)) %>% dplyr::group_by(!!sym(id)) %>% dplyr::summarise(Xi_mean = mean(!!sym(variable), na.rm = na.rm)) %>% dplyr::ungroup() %>% dplyr::pull("Xi_mean") -> between_ return(between_) } #' Compute the minimum between-group #' #' This function calculates the minimum between-group of a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the minimum between-group effect is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The minimum between-group effect. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' between_min(Gas, variable = "lgaspcar") #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' between_min(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export between_min <- function(data, variable, id=NULL, t=NULL, na.rm = FALSE) { return(min(xtbetween(data, variable, id, t, na.rm = na.rm), na.rm = na.rm)) } #' Compute the maximum between-group #' #' This function calculates the maximum between-group in a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the maximum between-group effect is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The maximum between-group effect. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' between_max(Gas, variable = "lgaspcar") #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' between_max(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export between_max <- function(data, variable, id=NULL, t=NULL, na.rm = FALSE) { return(max(xtbetween(data, variable, id, t, na.rm = na.rm), na.rm = na.rm)) } #' Compute the standard deviation of between-group #' #' This function calculates the standard deviation of between-group in a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the standard deviation of between-group effects is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The standard deviation of between-group effects. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' between_sd(Gas, variable = "lgaspcar") #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' between_sd(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export between_sd <- function(data, variable, id=NULL, t=NULL, na.rm = FALSE) { return(stats::sd(xtbetween(data, variable, id=id, t=t, na.rm = na.rm), na.rm = na.rm)) }
/scratch/gouwar.j/cran-all/cranData/xtsum/R/xtbetween.R
xtsum_ <- function(data, variable = NULL, id = NULL, t = NULL, na.rm = FALSE, dec = 3){ if(!"pdata.frame" %in% class(data)){ data <- plm::pdata.frame(data, index = c(id,t), drop.index = TRUE) } N <- sum(!is.na(xtwithin(data, variable, na.rm = na.rm))) n <- sum(!is.na(xtbetween(data, variable, na.rm = na.rm))) `T` <- round(N/n, dec) x_list <- list( "________" = c("Mean" = NA, "SD" = NA, "Min" = NA, "Max" = NA, "Observations" = NA), "Overal" = c("Mean" = round(mean(data[,variable], na.rm = na.rm),dec), "SD" = round(stats::sd(data[,variable], na.rm = na.rm),dec), "Min" = round(min(data[,variable], na.rm = na.rm),dec), "Max" = round(max(data[,variable], na.rm = na.rm),dec), "Observations" = paste("N =",N)), "between" = c("SD" = round(between_sd(data, variable, na.rm = na.rm),dec), "Min" = round(between_min(data, variable, na.rm = na.rm),dec), "Max" = round(between_max(data, variable, na.rm = na.rm),dec), "Observations" = paste("n =",n)), "within" = c("SD" = round(within_sd(data, variable, na.rm = na.rm),dec), "Min" = round(within_min(data, variable, na.rm = na.rm),dec), "Max" = round(within_max(data, variable, na.rm = na.rm),dec), "Observations" = paste("T =",`T`))) return(bind_cols("Variable" = c("___________",variable, NA, NA), "Dim" = c("_________", "overall", "between", "within"), bind_rows(x_list))) }
/scratch/gouwar.j/cran-all/cranData/xtsum/R/xtsum_x.R
#' Calculate summary statistics for panel data #' #' This function computes summary statistics for panel data, including overall #' statistics, between-group statistics, and within-group statistics. #' #' @param data A data.frame or pdata.frame object representing panel data. #' @param variables (Optional) Vector of variable names for which to calculate statistics. #' If not provided, all numeric variables in the data will be used. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' @param na.rm Logical indicating whether to remove NAs when calculating statistics. #' @param return.data.frame If the return object should be a dataframe #' @param dec Number of significant digits to report #' #' @return A table summarizing statistics for each variable, including Mean, SD, Min, and Max, #' broken down into Overall, Between, and Within dimensions. #' #' @examples #' #' # Using a data.frame and specifying variables, id, it, na.rm, dec #' data("nlswork", package = "sampleSelection") #' xtsum(nlswork, "hours", id = "idcode", t = "year", na.rm = TRUE, dec = 6) #' #' # Using pdata.frame object without specifying a variable #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' xtsum(Gas) #' #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' xtsum(Crime, variables = c("crmrte", "prbarr"), id = "county", t = "year") #' #' # Specifying variables to include in the summary #' xtsum(Gas, variables = c("lincomep", "lgaspcar")) #' #' @importFrom dplyr all_of select mutate group_by summarise ungroup pull sym bind_rows #' @importFrom knitr kable #' @importFrom magrittr %>% #' @importFrom plm pdata.frame index #' @importFrom kableExtra kable_classic kbl #' @importFrom sampleSelection treatReg #' @export xtsum <- function(data, variables = NULL, id = NULL, t = NULL, na.rm = FALSE, return.data.frame = FALSE, dec = 3) { # Check if data is a data.frame if (!is.data.frame(data)) { stop("data must be a data.frame object...") } # Check if id and t are provided if data is not a pdata.frame object if (any(is.null(id), is.null(t)) & !"pdata.frame" %in% class(data)) { stop("if data is not a pdata.frame object, id and t must be provided") } # If data is a pdata.frame object and id or t is missing, use pdata.frame index if ("pdata.frame" %in% class(data) & any(is.null(id), is.null(t))) { data$id <- plm::index(data)[1] %>% pull() data$t <- plm::index(data)[2] %>% pull() id <- "id" t <- "t" } # If variables are not specified, use all numeric variables in the data if (is.null(variables)) { numeric_cols <- colnames(data[,sapply(data, is.numeric)]) variables <- numeric_cols[!numeric_cols %in% c(id, t)] } idt <- c(id,t) # Initialize an empty data.frame for the table results TableRes = data.frame(matrix(nrow = 0, ncol = 6)) colnames(TableRes) <- c("Variable", "Dim", "Mean", "SD", "Min", "MAX") # Extract relevant data for specified variables data_ <- as.data.frame(data) %>% dplyr::select(dplyr::all_of(idt), dplyr::all_of(variables)) # Use sapply to calculate summary statistics for each variable sum_ <- sapply(variables, xtsum_, data=data_, id = id, t = t, na.rm = na.rm, dec = dec, simplify = FALSE, USE.NAMES = TRUE) # Set options for rendering NA values in the table opts <- options(knitr.kable.NA = "") if(return.data.frame){ return(do.call(bind_rows, sum_)) } else{ # Return the summary table using kableExtra return(kableExtra::kbl(do.call(bind_rows, sum_)) %>% kableExtra::kable_classic()) } }
/scratch/gouwar.j/cran-all/cranData/xtsum/R/xtsummary.R
#' @importFrom dplyr all_of select mutate group_by summarise ungroup pull sym bind_rows bind_cols #' @importFrom magrittr %>% #' @importFrom plm pdata.frame index #' @importFrom rlang .data #' xtwithin <- function(data, variable = NULL, id = NULL, t = NULL, na.rm = FALSE) { # Check if data is a data.frame if (!is.data.frame(data)) { stop("data must be a data.frame object...") } # Check if id and t are provided if data is not a pdata.frame object if (any(is.null(id), is.null(t)) & !"pdata.frame" %in% class(data)) { stop("if data is not a pdata.frame object, id and t must be provided") } # If data is a pdata.frame object and id or t is missing, use pdata.frame index if ("pdata.frame" %in% class(data) & any(is.null(id), is.null(t))) { data$id <- plm::index(data)[1] %>% pull() data$t <- plm::index(data)[2] %>% pull() id <- "id" t <- "t" } # If variables are not specified, use all numeric variables in the data idt <- c(id, t) data_ <- as.data.frame(data) %>% dplyr::select(dplyr::all_of(idt), dplyr::all_of(variable)) data %>% dplyr::select(all_of(idt), all_of(variable)) %>% dplyr::mutate(g_mean = mean(!!sym(variable), na.rm = na.rm)) %>% dplyr::group_by(!!sym(id)) %>% dplyr::mutate(Xi_mean = mean(!!sym(variable), na.rm = na.rm), within_x = !!sym(variable) - .data$Xi_mean + .data$g_mean) %>% dplyr::ungroup() %>% dplyr::pull("within_x") -> within_ return(within_) } #' Compute the minimum within-group for panel data #' #' This function computes the minimum within-group for a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the minimum within-group effect is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The minimum within-group effect. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' within_min(Gas, variable = "lgaspcar") #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' within_min(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export within_min <- function(data, variable, id = NULL, t = NULL, na.rm = FALSE) { return(min(xtwithin(data, variable, id, t, na.rm = na.rm), na.rm = na.rm)) } #' Compute the maximum within-group for a panel data #' #' This function computes the maximum within-group for a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the maximum within-group effect is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The maximum within-group effect. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' within_max(Gas, variable = "lgaspcar") #' #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' within_max(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export within_max <- function(data, variable, id = NULL, t = NULL, na.rm = FALSE) { return(max(xtwithin(data, variable, id, t, na.rm = na.rm), na.rm = na.rm)) } #' Compute the standard deviation of within-group for a panel data #' #' This function computes the standard deviation of within-group for a panel data. #' #' @param data A data.frame or pdata.frame object containing the panel data. #' @param variable The variable for which the standard deviation of within-group effects is calculated. #' @param na.rm Logical. Should missing values be removed? Default is FALSE. #' @param id (Optional) Name of the individual identifier variable. #' @param t (Optional) Name of the time identifier variable. #' #' @return The standard deviation of within-group effects. #' #' @examples #' # Example using pdata.frame #' data("Gasoline", package = "plm") #' Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) #' within_sd(Gas, variable = "lgaspcar") #' #' # Using regular data.frame with id and t specified #' data("Crime", package = "plm") #' within_sd(Crime, variable = "crmrte", id = "county", t = "year") #' #' @export within_sd <- function(data, variable, id = NULL, t = NULL, na.rm = FALSE) { return(stats::sd(xtwithin(data, variable, id, t, na.rm = na.rm), na.rm = na.rm)) }
/scratch/gouwar.j/cran-all/cranData/xtsum/R/xtwithin.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----eval=FALSE--------------------------------------------------------------- # install.packages("xtsum") # # # For dev version # # install.packages("devtools") # devtools::install_github("macosso/xtsum") ## ----message=FALSE, warning=FALSE--------------------------------------------- # Load the librarry library(xtsum) ## ----------------------------------------------------------------------------- data("nlswork", package = "sampleSelection") xtsum(nlswork, "hours", id = "idcode", t = "year", na.rm = T, dec = 6) ## ----fig.show='hold'---------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) xtsum(Gas) ## ----------------------------------------------------------------------------- data("Crime", package = "plm") xtsum(Crime, variables = c("polpc", "avgsen", "crmrte"), id = "county", t = "year") ## ----------------------------------------------------------------------------- xtsum(Gas, variables = c("lincomep", "lgaspcar")) ## ----fig.show='hold'---------------------------------------------------------- xtsum(Gas, variables = c("lincomep", "lgaspcar"), return.data.frame = TRUE) ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_max(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") between_max(Crime, variable = "crmrte", id = "county", t = "year") ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_min(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") between_min(Crime, variable = "crmrte", id = "county", t = "year") ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_sd(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") between_sd(Crime, variable = "crmrte", id = "county", t = "year") ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_max(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") within_max(Crime, variable = "crmrte", id = "county", t = "year") ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_min(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") within_min(Crime, variable = "crmrte", id = "county", t = "year") ## ----------------------------------------------------------------------------- data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_sd(Gas, variable = "lgaspcar") ## ----------------------------------------------------------------------------- data("Crime", package = "plm") within_sd(Crime, variable = "crmrte", id = "county", t = "year")
/scratch/gouwar.j/cran-all/cranData/xtsum/inst/doc/intro_to_xtsum.R
--- title: "introduction to xtsum" author: "Joao Claudio Macosso" date: "`r Sys.Date()`" output: rmarkdown::html_vignette bibliography: references.bib vignette: > %\VignetteIndexEntry{xtsum} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Introduction ```xtsum``` is an R wrapper based on ```STATA``` ```xtsum``` command, it used to provide summary statistics for a panel data set. It decomposes the variable $x_{it}$ into a between $(\bar{x_i})$ and within $(x_{it} − \bar{x_i} + \bar{\bar{x}})$, the global mean x being added back in make results comparable, see [@stata]. # Installation ```{r, eval=FALSE} install.packages("xtsum") # For dev version # install.packages("devtools") devtools::install_github("macosso/xtsum") ``` # Getting Started ```{r, message=FALSE, warning=FALSE} # Load the librarry library(xtsum) ``` ## xtsum This function computes summary statistics for panel data, including overall statistics, between-group statistics, and within-group statistics. **Usage** ``` xtsum( data, variables = NULL, id = NULL, t = NULL, na.rm = FALSE, return.data.frame = TRUE, dec = 3 ) ``` **Arguments** * ```data``` A data.frame or pdata.frame object representing panel data. * ``` variables``` (Optional) Vector of variable names for which to calculate statistics. If not provided, all numeric variables in the data will be used. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical indicating whether to remove NAs when calculating statistics. * ```return.data.frame``` If the return object should be a dataframe * ```dec``` Number of significant digits to report ### Example #### Genral example Based on National Longitudinal Survey of Young Women, 14-24 years old in 1968 ```{r} data("nlswork", package = "sampleSelection") xtsum(nlswork, "hours", id = "idcode", t = "year", na.rm = T, dec = 6) ``` The table above can be interpreted as below paraphrased from [@stata]. The overall and within are calculated over ```N = 28,467``` person-years of data. The between is calculated over ```n = 4,710``` persons, and the average number of years a person was observed in the hours data is```T = 6```. ```xtsum``` also reports standard deviation(```SD```), minimums(```Min```), and maximums(```Max```). Hours worked varied between ```Overal Min = 1``` and ```Overall Max = 168```. Average hours worked for each woman varied between ```between Min = 1``` and ```between Max = 83.5```. “Hours worked within” varied between ```within Min = −2.15``` and ```within Max = 130.1```, which is not to say that any woman actually worked negative hours. The within number refers to the deviation from each individual’s average, and naturally, some of those deviations must be negative. Then the negative value is not disturbing but the positive value is. Did some woman really deviate from her average by +130.1 hours? No. In our definition of within, we add back in the global average of 36.6 hours. Some woman did deviate from her average by 130.1 − 36.6 = 93.5 hours, which is still large. The reported standard deviations tell us that the variation in hours worked last week across women is nearly equal to that observed within a woman over time. That is, if you were to draw two women randomly from our data, the difference in hours worked is expected to be nearly equal to the difference for the same woman in two randomly selected years. More detailed interpretation can be found in handout[@stephenporter] #### Using pdata.frame object ```{r, fig.show='hold'} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) xtsum(Gas) ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") xtsum(Crime, variables = c("polpc", "avgsen", "crmrte"), id = "county", t = "year") ``` #### Specifying variables to include in the summary ```{r} xtsum(Gas, variables = c("lincomep", "lgaspcar")) ``` #### Returning a data.frame object Returning a data.frame might be useful if one wishes to perform additional manipulation with the data or if you intend to use other rporting packages such as stargazer [@hlavac_2018_stargazer] or kabel[@zhu_2021_create]. ```{r, fig.show='hold'} xtsum(Gas, variables = c("lincomep", "lgaspcar"), return.data.frame = TRUE) ``` # Other Functions The functions below can serve as a helper when the user is not interested in a full report but rather check a specific value. ## between_max This function computes the maximum between-group in a panel data. *Usage* ```between_max(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data```: A data.frame or pdata.frame object containing the panel data. * ```variable```: The variable for which the maximum between-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_max(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_max(Crime, variable = "crmrte", id = "county", t = "year") ``` ## between_min This function computes the minimum between-group of a panel data. *Usage* ```between_min(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the minimum between-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The minimum between-group effect. #### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_min(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_min(Crime, variable = "crmrte", id = "county", t = "year") ``` ## between_sd This function calculates the standard deviation of between-group in a panel data. *Usage* ```between_sd(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the standard deviation of between-group effects is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The standard deviation of between-group effects. ### Examples #### using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_sd(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_sd(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_max This function computes the maximum within-group for a panel data. *Usage* ```within_max(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the maximum within-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The maximum within-group effect. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_max(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_max(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_min This function computes the minimum within-group for a panel data. *Usage* ```within_min(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the minimum within-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The minimum within-group effect. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_min(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_min(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_sd This function computes the standard deviation of within-group for a panel data. *Usage* ```within_sd(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data```A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the standard deviation of within-group effects is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The standard deviation of within-group effects. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_sd(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_sd(Crime, variable = "crmrte", id = "county", t = "year") ``` # References
/scratch/gouwar.j/cran-all/cranData/xtsum/inst/doc/intro_to_xtsum.Rmd
--- title: "introduction to xtsum" author: "Joao Claudio Macosso" date: "`r Sys.Date()`" output: rmarkdown::html_vignette bibliography: references.bib vignette: > %\VignetteIndexEntry{xtsum} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Introduction ```xtsum``` is an R wrapper based on ```STATA``` ```xtsum``` command, it used to provide summary statistics for a panel data set. It decomposes the variable $x_{it}$ into a between $(\bar{x_i})$ and within $(x_{it} − \bar{x_i} + \bar{\bar{x}})$, the global mean x being added back in make results comparable, see [@stata]. # Installation ```{r, eval=FALSE} install.packages("xtsum") # For dev version # install.packages("devtools") devtools::install_github("macosso/xtsum") ``` # Getting Started ```{r, message=FALSE, warning=FALSE} # Load the librarry library(xtsum) ``` ## xtsum This function computes summary statistics for panel data, including overall statistics, between-group statistics, and within-group statistics. **Usage** ``` xtsum( data, variables = NULL, id = NULL, t = NULL, na.rm = FALSE, return.data.frame = TRUE, dec = 3 ) ``` **Arguments** * ```data``` A data.frame or pdata.frame object representing panel data. * ``` variables``` (Optional) Vector of variable names for which to calculate statistics. If not provided, all numeric variables in the data will be used. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical indicating whether to remove NAs when calculating statistics. * ```return.data.frame``` If the return object should be a dataframe * ```dec``` Number of significant digits to report ### Example #### Genral example Based on National Longitudinal Survey of Young Women, 14-24 years old in 1968 ```{r} data("nlswork", package = "sampleSelection") xtsum(nlswork, "hours", id = "idcode", t = "year", na.rm = T, dec = 6) ``` The table above can be interpreted as below paraphrased from [@stata]. The overall and within are calculated over ```N = 28,467``` person-years of data. The between is calculated over ```n = 4,710``` persons, and the average number of years a person was observed in the hours data is```T = 6```. ```xtsum``` also reports standard deviation(```SD```), minimums(```Min```), and maximums(```Max```). Hours worked varied between ```Overal Min = 1``` and ```Overall Max = 168```. Average hours worked for each woman varied between ```between Min = 1``` and ```between Max = 83.5```. “Hours worked within” varied between ```within Min = −2.15``` and ```within Max = 130.1```, which is not to say that any woman actually worked negative hours. The within number refers to the deviation from each individual’s average, and naturally, some of those deviations must be negative. Then the negative value is not disturbing but the positive value is. Did some woman really deviate from her average by +130.1 hours? No. In our definition of within, we add back in the global average of 36.6 hours. Some woman did deviate from her average by 130.1 − 36.6 = 93.5 hours, which is still large. The reported standard deviations tell us that the variation in hours worked last week across women is nearly equal to that observed within a woman over time. That is, if you were to draw two women randomly from our data, the difference in hours worked is expected to be nearly equal to the difference for the same woman in two randomly selected years. More detailed interpretation can be found in handout[@stephenporter] #### Using pdata.frame object ```{r, fig.show='hold'} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) xtsum(Gas) ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") xtsum(Crime, variables = c("polpc", "avgsen", "crmrte"), id = "county", t = "year") ``` #### Specifying variables to include in the summary ```{r} xtsum(Gas, variables = c("lincomep", "lgaspcar")) ``` #### Returning a data.frame object Returning a data.frame might be useful if one wishes to perform additional manipulation with the data or if you intend to use other rporting packages such as stargazer [@hlavac_2018_stargazer] or kabel[@zhu_2021_create]. ```{r, fig.show='hold'} xtsum(Gas, variables = c("lincomep", "lgaspcar"), return.data.frame = TRUE) ``` # Other Functions The functions below can serve as a helper when the user is not interested in a full report but rather check a specific value. ## between_max This function computes the maximum between-group in a panel data. *Usage* ```between_max(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data```: A data.frame or pdata.frame object containing the panel data. * ```variable```: The variable for which the maximum between-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_max(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_max(Crime, variable = "crmrte", id = "county", t = "year") ``` ## between_min This function computes the minimum between-group of a panel data. *Usage* ```between_min(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the minimum between-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The minimum between-group effect. #### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_min(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_min(Crime, variable = "crmrte", id = "county", t = "year") ``` ## between_sd This function calculates the standard deviation of between-group in a panel data. *Usage* ```between_sd(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the standard deviation of between-group effects is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The standard deviation of between-group effects. ### Examples #### using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) between_sd(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") between_sd(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_max This function computes the maximum within-group for a panel data. *Usage* ```within_max(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the maximum within-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The maximum within-group effect. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_max(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_max(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_min This function computes the minimum within-group for a panel data. *Usage* ```within_min(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data``` A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the minimum within-group effect is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The minimum within-group effect. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_min(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_min(Crime, variable = "crmrte", id = "county", t = "year") ``` ## within_sd This function computes the standard deviation of within-group for a panel data. *Usage* ```within_sd(data, variable, id = NULL, t = NULL, na.rm = FALSE)``` *Arguments* * ```data```A data.frame or pdata.frame object containing the panel data. * ```variable``` The variable for which the standard deviation of within-group effects is calculated. * ```id``` (Optional) Name of the individual identifier variable. * ```t``` (Optional) Name of the time identifier variable. * ```na.rm``` Logical. Should missing values be removed? Default is FALSE. *Value* The standard deviation of within-group effects. ### Example #### Using pdata.frame ```{r} data("Gasoline", package = "plm") Gas <- pdata.frame(Gasoline, index = c("country", "year"), drop.index = TRUE) within_sd(Gas, variable = "lgaspcar") ``` #### Using regular data.frame with id and t specified ```{r} data("Crime", package = "plm") within_sd(Crime, variable = "crmrte", id = "county", t = "year") ``` # References
/scratch/gouwar.j/cran-all/cranData/xtsum/vignettes/intro_to_xtsum.Rmd
#' Extract model coefficients from fitted \code{xtune} object #' #' \code{coef_xtune} extracts model coefficients from objects returned by \code{xtune} object. #' @param object Fitted 'xtune' model object. #' @param ... Not used #' @details \code{coef} and \code{predict} methods are provided as a convenience to extract coefficients and make prediction. \code{coef.xtune} simply extracts the estimated coefficients returned by \code{xtune}. #' @return Coefficients extracted from the fitted model. #' @seealso \code{xtune}, \code{predict_xtune} #' @examples #' # See examples in \code{predict_xtune}. #' @export coef_xtune <- function(object,...) { beta.est <- object$beta.est return(drop(beta.est)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/coef.xtune.R
#' Estimate noise variance given predictor X and continuous outcome Y. #' #' \code{estimateVariance} estimate noise variance. #' @param X predictor matrix of dimension \eqn{n} by \eqn{p}. #' @param Y continuous outcome vector of length \eqn{n}. #' @param n_rep number of repeated estimation. Default is 10. #' @details The \code{estimateSigma} function from \link{selectiveInference} is used repeatedly to estimate noise variance. #' @return Estimated noise variance of X and Y. #' @references Stephen Reid, Jerome Friedman, and Rob Tibshirani (2014). A study of error variance estimation in lasso regression. arXiv:1311.5274. #' @seealso \link{selectiveInference} #' @examples #' ## simulate some data #' set.seed(9) #' n = 30 #' p = 10 #' sigma.square = 1 #' X = matrix(rnorm(n*p),n,p) #' beta = c(2,-2,1,-1,rep(0,p-4)) #' Y = X%*%beta + rnorm(n,0,sqrt(sigma.square)) #' #' ## estimate sigma square #' sigma.square.est = estimateVariance(X,Y) #' sigma.square.est #' @importFrom selectiveInference estimateSigma #' @export estimateVariance <- function(X, Y, n_rep = 5) { Y <- as.double(drop(Y)) dimY = dim(Y) nrowY = ifelse(is.null(dimY), length(Y), dimY[1]) if (nrowY < 10) { stop("Need at least 10 observations to estimate variance") } temp = array(NA, n_rep) for (i in 1:n_rep) { c = suppressWarnings(estimateSigma(X, Y)$sigmahat^2) temp[i] = ifelse(is.infinite(c), NA, c) } return(mean(temp, na.rm = T)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/estimate_variance.R
#' An simulated example dataset #' #' The simulated \code{example} data contains 100 observations, 200 predictors, and an continuous outcome. Z contains 3 columns, each column is #' indicator variable (can be viewed as the grouping of predictors). #' #' @docType data #' #' @usage data(example) #' #' @keywords datasets #' #' @format The \code{example} object is a list containing three elements: #' \itemize{ #' \item X: A simulated 100 by 200 matrix #' \item Y: Continuous response vector of length 100 #' \item Z: A 200 by 3 matrix. Z_jk indicates whether predictor X_j has external variable Z_k or not. #' } #' #' @examples #' data(example) #' X <- example$X #' Y <- example$Y #' Z <- example$Z #' \donttest{xtune(X,Y,Z)} "example"
/scratch/gouwar.j/cran-all/cranData/xtune/R/example_data.R
#' Simulated diet data to predict weight loss #' #' The simulated \code{diet} data contains 100 observations, 14 predictors, #' and an binary outcome, weightloss. The external information Z is the nutrition fact about the dietary items. #' Z contains three external information variables: Calories, protein and carbohydrates. #' #' @docType data #' #' @usage data(diet) #' #' @keywords datasets #' #' @format The \code{diet} object is a list containing three elements: #' \itemize{ #' \item DietItems: Matrix of predictors. #' \item weightloss: 0: no weight loss; 1: weight loss #' \item nutritionFact: External information of the predictors #' } #' @references S. Witte, John & Greenland, Sander & W. Haile, Robert & L. Bird, Cristy. (1994). Hierarchical Regression Analysis Applied to a Study of Multiple Dietary Exposures and Breast Cancer. Epidemiology (Cambridge, Mass.). 5. 612-21. 10.1097/00001648-199411000-00009. #' @seealso \code{\link{example}} #' @examples #' data(diet) #' X <- diet$DietItems #' Y <- diet$weightloss #' Z <- diet$nutritionFact #' \donttest{fit <- xtune(X,Y,Z, family = "binary")} #' \donttest{fit$penalty.vector} "diet"
/scratch/gouwar.j/cran-all/cranData/xtune/R/example_diet.R
#' Simulated gene data to predict weight loss #' #' The simulated \code{gene} data contains 50 observations, 200 predictors, #' and an continuous outcome, bone mineral density. The external information Z is four previous study results that identifies the biological importance of genes. #' #' @docType data #' #' @usage data(gene) #' #' @keywords datasets #' #' @format The \code{gene} object is a list containing three elements: #' \itemize{ #' \item GeneExpression: Matrix of gene expression predictors. #' \item bonedensity: Continuous outcome variable #' \item PreviousStudy: Whether each gene is identified by previous study results. #' } #' @seealso \code{\link{diet}} #' @examples #' data(gene) #' X <- gene$GeneExpression #' Y <- gene$bonedensity #' Z <- gene$PreviousStudy #' \donttest{fit <- xtune(X,Y,Z)} #' \donttest{fit$penalty.vector} "gene"
/scratch/gouwar.j/cran-all/cranData/xtune/R/example_gene.R
#' Simulated data with multi-categorical outcome #' #' The simulated data contains 600 observations, 800 predictors, 10 covariates, #' and an multiclass outcome with three categories. The external information Z contains five indicator prior covariates. #' #' @docType data #' #' @usage data(example.multiclass) #' #' @keywords datasets #' #' @format The \code{example.multiclass} object is a list containing three elements: #' \itemize{ #' \item X: A simulated 600 by 800 matrix #' \item Y: Categorical outcome with three levels #' \item U: Covariates matrix with 600 by 10 dimension, will be forced in the model #' \item Z: A 800 by 5 matrix with indicator entries. #' } #' #' @examples #' data(example.multiclass) #' X <- example.multiclass$X #' Y <- example.multiclass$Y #' U <- example.multiclass$U #' Z <- example.multiclass$Z #' \donttest{fit <- xtune(X = X,Y = Y, U = U, Z = Z, family = "multiclass", c = 0.5)} #' \donttest{fit$penalty.vector} "example.multiclass"
/scratch/gouwar.j/cran-all/cranData/xtune/R/example_multiclass.R
##------------ xtune.fit utility functions approx_likelihood.xtune <- function(to_estimate, input_X, input_Y, input_Z, sigma.square.est, input_c) { X = input_X Y = input_Y Z = input_Z c = input_c sigma_square = sigma.square.est n = nrow(X) lambda = exp(Z %*% to_estimate) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) K = sigma_square * diag(n) + X %*% diag(c(gamma)) %*% t(X) logdetK = determinant(K)$modulus[1] part1 = t(Y) %*% solve(K, Y) normapprox = 1/2 * (part1 + logdetK) return(as.numeric(normapprox)) } update_alpha.xtune <- function(X, Y, Z,c,alpha.old, alpha.max, epsilon, sigma.square, theta, maxstep_inner, margin_inner, verbosity) { ## initial alpha.inner.old = alpha.old k_inner = 1 n = nrow(X) p = ncol(X) while (k_inner < maxstep_inner) { # given alpha update delta lambda = exp(Z %*% alpha.inner.old) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) sd_y <- sqrt(var(Y) * (n - 1)/n) C = sum(1/gamma)/p * sd_y * sigma.square/n delta.est = coef(glmnet(X, Y, alpha = 0, penalty.factor = 1/gamma, lambda = C, standardize = F, intercept = FALSE))[-1] ## given delta update alpha alpha.inner.new <- optim(alpha.old, likelihood.alpha.theta.xtune,likelihood.alpha.theta.gradient.xtune, c =c,Z = Z, theta = theta, delta = delta.est,method = "L-BFGS-B", upper = c(alpha.max*epsilon, rep(Inf, length(alpha.old)-1)))$par if (sum(abs(alpha.inner.new - alpha.inner.old)) < margin_inner) { break } if (verbosity == TRUE) { cat(blue$italic("#-----------------"),magenta("Inner loop Iteration",k_inner,"Done"),blue$italic("-----------------#\n"),sep = "") } k_inner = k_inner + 1 alpha.inner.old <- alpha.inner.new } return(list(alpha.est = alpha.inner.old, inner_iter = k_inner)) } likelihood.alpha.theta.xtune <- function(Z,c, alpha, theta, delta) { lambda = exp(Z %*% alpha) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) return(as.numeric(t(theta) %*% gamma + delta^2 %*% (1/gamma))) } likelihood.alpha.theta.gradient.xtune <- function(Z,c, alpha, theta, delta) { lambda = exp(Z %*% alpha) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) dev_gamma = theta - delta^2/(gamma^2) dev_gamma_alpha = as.vector((-2*(2*(1-c) + 2*c^2*lambda))/(2*lambda*(1-c) + (c*lambda)^2)^2 *lambda) *Z return(crossprod(dev_gamma, dev_gamma_alpha)) } score_function <- function(to_estimate, input_X, input_Y, input_Z, sigma.square.est, input_c) { X = input_X Y = input_Y Z = input_Z c = input_c sigma_square = sigma.square.est n = nrow(X) p = ncol(X) lambda = exp(Z %*% to_estimate) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) Rinv <- backsolve(chol(crossprod(X)/sigma_square + diag(c(1/gamma))), diag(1, p)) diagSigma <- rowSums(Rinv^2) mu_vec <- (Rinv %*% (crossprod(Rinv, crossprod(X, Y))))/sigma_square dev_gamma = (gamma - diagSigma - mu_vec^2)/(gamma^2) return(-crossprod(dev_gamma, as.vector(gamma) * Z)) } relative_change<-function(a,b){ return((a-b)/b) } ##------------ mxtune.fit utility functions estimate.alpha.mxtune <- function(X,Y,Z,c,B_inv, alpha.init, alpha.max, epsilon, maxstep, margin, maxstep_inner, margin_inner, compute.likelihood, verbosity){ n = nrow(X);p=ncol(X);k = ncol(B_inv) ## Initialize alpha.old = alpha.init itr = 1 while(itr < maxstep){ # Given alpha, update theta lambda = exp(Z%*%alpha.old) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) Sigma_y = apply(B_inv, 2 , function(g) list(diag(g) + (t(t(X)*c(gamma)))%*%t(X))) theta = t(sapply(Sigma_y, function(g) colSums(X*solve(g[[1]],X)))) # Given theta, update alpha update.result <-update_alpha.mxtune(X,Y,Z,c = c,B_inv = B_inv, alpha.old = alpha.old,alpha.max, theta = theta, epsilon = epsilon, maxstep_inner = maxstep_inner,margin_inner = margin_inner) alpha.new <- update.result$alpha.est # Check convergence if(sum(abs(alpha.new - alpha.old)) < margin ){ break } alpha.old <- alpha.new if (verbosity == TRUE) { cat(blue$italic("#-----------------"),magenta("Inner loop Iteration",itr,"Done"),blue$italic("-----------------#\n"),sep = "") } itr <- itr+1 } return(alpha.new) } update_alpha.mxtune<-function(X,Y,Z,c,B_inv,alpha.old,alpha.max, theta, epsilon, maxstep_inner,margin_inner){ ## initial alpha.iner.old = alpha.old i_inner = 1 n=nrow(X) p=ncol(X) k = ncol(B_inv) B = 1/B_inv while (i_inner < maxstep_inner){ # given alpha update delta lambda = exp(Z%*%alpha.iner.old) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) X_B_sqrt = NULL; Y_B_sqrt = NULL; sd_y = NULL; C = NULL;delta.est = NULL for (i in 1:k) { X_B_sqrt[[i]] = X*sqrt(B[,i]) Y_B_sqrt[[i]] = Y[,i]*sqrt(B[,i]) sd_y[[i]] <- sqrt(var(Y_B_sqrt[[i]])*(n-1)/n) C[[i]]=sum(1/gamma)/p* sd_y[[i]]*1/n delta.est[[i]]=coef(glmnet(X_B_sqrt[[i]],Y_B_sqrt[[i]],alpha=0, penalty.factor = 1/gamma,lambda = C[[i]], standardize = F, intercept = FALSE))[-1] } ## given delta update alpha with constrain alpha.iner.new <- optim(alpha.old,likelihood.alpha.theta.mxtune,likelihood.alpha.theta.gradient.mxtune,c =c,Z=Z,theta = theta,delta=delta.est, k = k,method = "L-BFGS-B", upper = c(alpha.max*epsilon, rep(Inf, length(alpha.old)-1)))$par if (sum(abs(alpha.iner.new - alpha.iner.old)) < margin_inner){ break } i_inner = i_inner + 1 alpha.iner.old <- alpha.iner.new } return(list(alpha.est=alpha.iner.old,inner_iter = i_inner)) } likelihood.alpha.theta.mxtune<-function(Z,c,alpha,theta,delta,k){ lambda = exp(Z %*% alpha) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) L.theta.alpha = NULL for (i in 1:k) { L.theta.alpha[i] = t(theta[i,])%*%gamma + delta[[i]]^2%*%(1/gamma) } return(as.numeric(sum(L.theta.alpha))) } likelihood.alpha.theta.gradient.mxtune<-function(Z,c,alpha,theta,delta,k){ lambda = exp(Z %*% alpha) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) dev_gamma_alpha = as.vector((-2*(2*(1-c) + 2*c^2*lambda))/(2*lambda*(1-c) + (c*lambda)^2)^2 *lambda) *Z dev_gamma = NULL;L.prime = NULL for (i in 1:k) { dev_gamma[[i]] = theta[i,] - delta[[i]]^2/(gamma^2) } L.prime = t(sapply(dev_gamma, function(g) crossprod(g, dev_gamma_alpha))) return(colSums(L.prime)) } approx_likelihood.mxtune <- function(B_inv,X,Y,V_inv,k,n) { normapprox = NULL for (i in 1:k) { K = B_inv[,i] + X %*% V_inv %*% t(X) logdetK = determinant(K)$modulus[1] part1 = t(as.numeric(Y[,i])) %*% solve(K, Y[,i]) normapprox[i] = part1 + logdetK } return(-0.5*n*log(2*pi) + sum(as.numeric(normapprox))) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/helper_func.R
#' Calculate misclassification error #' #' \code{misclassification} calculate misclassification error between predicted class and true class #' @param pred Predicted class #' @param true Actual class #' @return Misclassification error for binary or multiclass outcome. #' @seealso To calculate the Area Under the Curve (AUC) for binary or multiclass outcomes, please refer to the \code{pROC}. #' @examples #' Y1 <- rbinom(10,1,0.5) #' Y2 <- rnorm(10,1,0.5) #' misclassification(Y1,Y2) #' @export misclassification <- function(pred, true) { n_pred = ifelse(is.null(dim(pred)), length(pred), dim(pred)[1]) n_true = ifelse(is.null(dim(true)), length(true), dim(true)[1]) if (length(pred) != length(true)) { stop("The length of prediction class and actual class does not match") } else if (sum(is.na(pred)) > 0) { warning("Prediction class contain missing value") } else if (sum(is.na(true)) > 0) { warning("Actual class contain missing value") } return(mean(pred != true, na.rm = T)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/misclassification.R
#' Calculate mean square error #' #' \code{mse} calculate mean square error (MSE) between prediction values and true values for linear model #' @param pred Prediction values vector #' @param true Actual values vector #' @return mean square error #' @examples #' Y1 <- rnorm(10,0,1) #' Y2 <- rnorm(10,0,1) #' mse(Y1,Y2) #' @export mse <- function(pred, true) { n_pred = ifelse(is.null(dim(pred)), length(pred), dim(pred)[1]) n_true = ifelse(is.null(dim(true)), length(true), dim(true)[1]) if (length(pred) != length(true)) { stop("The length of prediction values and actual values does not match") } else if (sum(is.na(pred)) > 0) { warning("Prediction values contain missing value") } else if (sum(is.na(true)) > 0) { warning("Actual values contain missing value") } return(mean((as.vector(pred) - as.vector(true))^2, na.rm = T)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/mse.R
#' @import glmnet crayon selectiveInference #' @importFrom stats optim coef var predict mxtune.fit <- function(X, Y, Z, U, c, epsilon, max_s, margin_s, alpha.est.init, maxstep, margin, maxstep_inner, margin_inner, compute.likelihood, verbosity, standardize = standardize, intercept = intercept) { n = nrow(X) p=ncol(X) k = length(unique(Y)) ##------------ Multiclass elastic-net regression ## Initialize alpha.est.old = alpha.est.init likelihood.score = c() s = 1 ## calculate alpha.max a.max = NULL for (i in 1:k) { y.temp = ifelse(Y==unique(Y)[i],1,0) a.max = cbind(a.max, max( abs(t(y.temp - mean(y.temp)*(1-mean(y.temp))) %*% X ) )/ (c * n)) } alpha.max = min(max(abs(a.max))/abs(ifelse(Z==0,0.01,Z))) ## start estimation cat(yellow$italic$bold("Start estimating alpha:\n")) while (s < max_s){ # iteratively compute alpha and beta mode # Given alpha, update beta mode, Y hat etc lambda = exp(Z%*%alpha.est.old) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) A = (lambda^2*c^2 + 2*lambda*(1-c))/2 # use the glmnet to update beta.mode mode.est=coef(glmnet(X,Y,alpha=0, family = 'multinomial',penalty.factor = A,lambda = sum(A)/p/n, standardize = F, intercept = FALSE)) cat.prob = sapply(mode.est, function(g) exp(X%*%g[-1])) t.mode = cat.prob/rowSums(cat.prob) # softmax function B_inv = apply(t.mode, 2, function(g) as.vector(1/(g*(1-g)))) Y_HAT = NULL for (i in 1:k) { y = ifelse(Y==names(mode.est)[i],1,0) cat.y = X%*%mode.est[[i]][-1] + B_inv[,i]*(y - t.mode[,i]) Y_HAT = cbind(Y_HAT,cat.y) } if(compute.likelihood == TRUE){ V_inv = diag(as.vector(gamma)) likelihood.score = c(approx_likelihood.mxtune(B_inv,X,Y_HAT,V_inv,k,n),likelihood.score) } # Given beta mode, Y hat etc, update alpha alpha.est.new <- estimate.alpha.mxtune(X,Y_HAT,Z,c = c,B_inv,alpha.init = alpha.est.old, alpha.max, epsilon = epsilon, maxstep = maxstep, margin = margin, maxstep_inner = maxstep_inner, margin_inner = margin_inner, compute.likelihood = F,verbosity = verbosity) # Check convergence if(sum(abs(alpha.est.new - alpha.est.old)) < margin_s ){ cat(red$bold("Done!\n")) break } alpha.est.old <- alpha.est.new # Track iteration progress if (verbosity == TRUE) { cat(green$italic("#---"),green$bold("Outer loop Iteration",s,"Done"),green$italic("---#\n"),sep = "") } s <- s+1 } tauEst = exp(Z%*%alpha.est.old) pen_vec= tauEst/n if(is.null(U)) {pen_vec_cov = pen_vec} else {pen_vec_cov = c(pen_vec, rep(0,ncol(U)))} pen_vec_cov[pen_vec_cov > 1e3] <- 1e3 C = sum(pen_vec_cov)/p obj = glmnet(cbind(X, U),Y,family = "multinomial",alpha = c, lambda = C, penalty.factor = pen_vec_cov, type.measure="mae") cus.coef = coef(obj,x=cbind(X, U),y=Y,family = "multinomial",alpha = c, exact=TRUE,s= C, penalty.factor = pen_vec_cov,standardize=standardize,intercept = intercept) return(list(model = obj, beta.est = cus.coef, penalty.vector = pen_vec_cov, lambda = C, alpha.est = alpha.est.old, n_iter = s-1,likelihood.score = likelihood.score, sigma.square = NULL)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/mxtune_fit.R
#' Model predictions based on fitted \code{xtune} object #' #' \code{predict_xtune} produces predicted values fitting an xtune model to a new dataset #' @param object Fitted 'xtune' model object. #' @param newX Matrix of values at which predictions are to be made. #' @param type Type of prediction required. For "linear" models it gives the fitted values. Type "response" gives the fitted probability scores of each category for "binary" or "multiclass" outcome. Type "class" applies to "binary" or "multiclass" models, and produces the class label corresponding to the maximum probability. #' @param ... Not used #' @details \code{coef} and \code{predict} methods are provided as a convenience to extract coefficients and make prediction. \code{predict_xtune} simply calculate the predicted value using the estimated coefficients returned by \code{xtune}. #' @return A vector of predictions #' @seealso \code{xtune}, \code{coef_xtune} #' @examples #' #' ## If no Z provided, perform Empirical Bayes tuning #' ## simulate linear data #' set.seed(9) #' data(example) #' X <- example$X #' Y <- example$Y #' Z <- example$Z #' #' \donttest{ #' fit.eb <- xtune(X,Y) #' coef_xtune(fit.eb) #' predict_xtune(fit.eb,X) #' } #' #' #' ## Feature specific shrinkage based on external information Z: #' #' ## simulate multi-categorical data #' data(example.multiclass) #' X <- example.multiclass$X #' Y <- example.multiclass$Y #' Z <- example.multiclass$Z #' \donttest{ #' fit <- xtune(X,Y,Z,family = "multiclass") #' #' #' ## Coef and predict methods #' coef_xtune(fit) #' predict_xtune(fit,X, type = "class") #' } #' @export predict_xtune <- function(object, newX, type = c("response","class"), ...) { type = match.arg(type) ## check new X input if (missing(newX)){ stop("You need to supply a value for 'newX'") } else if (!(typeof(newX) %in% c("double", "integer"))) { stop("New X contains non-numeric values") } else if (!is.matrix(newX)) { stop("New X is not a matrix") } else if (object$family == "linear") { if(length(object$beta.est[-1]) != ncol(newX)){ stop("New X does not have the same number of columns as X train") } } else if (object$family != "linear"){ if(length(object$beta.est[[1]][-1]) != ncol(newX)){ stop("New X does not have the same number of columns as X train") } } # Check the family of Y if (type == "class" & object$family == "binary"){ predicted <- predict(object$model, newx = newX, s = object$lambda, type = "class") } else if(type == "response" & object$family == "binary"){ predicted <- as.data.frame(predict(object$model, newx = newX, s = object$lambda, type = "response")) } else if(type == "class" & object$family == "multiclass"){ predicted <- predict(object$model, newx = newX, s = object$lambda, type = "class") } else if(type == "response" & object$family == "multiclass"){ predicted <- as.data.frame(predict(object$model, newx = newX, s = object$lambda, type = "response")) } else { predicted <- object$beta.est[1] + newX %*% object$beta.est[-1] } return(drop(predicted)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/predict.xtune.R
#' Regularized regression incorporating external information #' #' \code{xtune} uses an Empirical Bayes approach to integrate external information into regularized regression models for both linear and categorical outcomes. It fits models with feature-specific penalty parameters based on external information. #' @param X Numeric design matrix of explanatory variables (\eqn{n} observations in rows, \eqn{p} predictors in columns). \code{xtune} includes an intercept by default. #' @param Y Outcome vector of dimension \eqn{n}. #' @param Z Numeric information matrix about the predictors (\eqn{p} rows, each corresponding to a predictor in X; \eqn{q} columns of external information about the predictors, such as prior biological importance). If Z is the grouping of predictors, it is best if user codes it as a dummy variable (i.e. each column indicating whether predictors belong to a specific group). #' @param U Covariates to be adjusted in the model (matrix with \eqn{n} observations in rows, \eqn{u} predictors in columns). Covariates are non-penalized in the model. #' @param family The family of the model according to different types of outcomes including "linear", "binary", and "multiclass". #' @param c The elastic-net mixing parameter ranging from 0 to 1. When \eqn{c} = 1, the model corresponds to Lasso. When \eqn{c} is set to 0, it corresponds to Ridge. For values between 0 and 1 (with a default of 0.5), the model corresponds to the elastic net. #' @param epsilon The parameter controls the boundary of the \code{alpha}. The maximum value that \code{alpha} could achieve equals to epsilon times of alpha max calculated by the pathwise coordinate descent. A larger value of epsilon indicates a stronger shrinkage effect (with a default of 5). #' @param sigma.square A user-supplied noise variance estimate. Typically, this is left unspecified, and the function automatically computes an estimated sigma square values using R package \code{selectiveinference}. #' @param message Generates diagnostic message in model fitting. Default is TRUE. #' @param control Specifies \code{xtune} control object. See \code{\link{xtune.control}} for more details. #' @details \code{xtune} has two main usages: #' \itemize{ #' \item The basic usage of it is to choose the tuning parameter \eqn{\lambda} in elastic net regression using an #' Empirical Bayes approach, as an alternative to the widely-used cross-validation. This is done by calling \code{xtune} without specifying external information matrix Z. #' #' \item More importantly, if an external information Z about the predictors X is provided, \code{xtune} can allow predictor-specific shrinkage #' parameters for regression coefficients in penalized regression models. The idea is that Z might be informative for the effect-size of regression coefficients, therefore we can guide the penalized regression model using Z. #' } #' #' Please note that the number of rows in Z should match with the number of columns in X. Since each column in Z is a feature about X. \href{https://github.com/JingxuanH/xtune}{See here for more details on how to specify Z}. #' #' A majorization-minimization procedure is employed to fit \code{xtune}. #' @return An object with S3 class \code{xtune} containing: #' \item{beta.est}{The fitted vector of coefficients.} #' \item{penalty.vector}{The estimated penalty vector applied to each regression coefficient. Similar to the \code{penalty.factor} argument in \link{glmnet}.} #' \item{lambda}{The estimated \eqn{\lambda} value. Note that the lambda value is calculated to reflect that the fact that penalty factors are internally rescaled to sum to nvars in \link{glmnet}. Similar to the \code{lambda} argument in \link{glmnet}.} #' \item{alpha.est}{The estimated second-level coefficient for prior covariate Z. The first value is the intercept of the second-level coefficient.} #' \item{n_iter}{Number of iterations used until convergence.} #' \item{method}{Same as in argument above} #' \item{sigma.square}{The estimated sigma square value using \code{\link{estimateVariance}}, if \code{sigma.square} is left unspecified. When \code{family} equals to "binary" or "multiclass", the \code{sigma.square} equals to NULL.} #' \item{family}{same as above} #' \item{likelihood.score}{A vector containing the marginal likelihood value of the fitted model at each iteration.} #' @author Jingxuan He and Chubing Zeng #' @seealso \link{predict_xtune}, as well as \link{glmnet}. #' @examples #' ## use simulated example data #' set.seed(1234567) #' data(example) #' X <- example$X #' Y <- example$Y #' Z <- example$Z #' #' ## Empirical Bayes tuning to estimate tuning parameter, as an alternative to cross-validation: #' \donttest{ #' fit.eb <- xtune(X=X,Y=Y, family = "linear") #' fit.eb$lambda #' } #' #' ### compare with tuning parameter chosen by cross-validation, using glmnet #' \donttest{ #' fit.cv <- glmnet::cv.glmnet(x=X,y=Y,alpha = 0.5) #' fit.cv$lambda.min #' } #' #' ## Feature-specific penalties based on external information Z: #' \donttest{ #' fit.diff <- xtune(X=X,Y=Y,Z=Z, family = "linear") #' fit.diff$penalty.vector #' } #' #' @import glmnet crayon selectiveInference lbfgs #' @importFrom stats optim #' @export #' #' xtune <- function(X, Y, Z = NULL,U = NULL, family=c("linear","binary","multiclass"), c = 0.5, epsilon = 5, sigma.square = NULL, message = TRUE, control = list()) { # function call this.call <- match.call() family = match.arg(family) # check user inputs Check X, X need to be a matrix or data.frame np = dim(X) if (is.null(np) | (np[2] <= 1)) stop("X must be a matrix with 2 or more columns") nobs = as.integer(np[1]) nvar = as.integer(np[2]) ## Check Y if (length(unique(Y)) == 2 & family == "linear"){ warning(paste("Y only has two unique values, coerce the family to binary")) family = "binary" } ## Check if the numbers of observation of X and Y are consistent dimY = dim(Y) nrowY = ifelse(is.null(dimY), length(Y), dimY[1]) if (nrowY != nobs) stop(paste("number of observations in Y (", nrowY, ") not equal to the number of rows of X (", nobs, ")", sep = "")) # Check Z If no Z provided, then provide Z of a single column of 1 if (is.null(Z)) { if (message == TRUE){ cat("No Z matrix provided, only a single tuning parameter will be estimated using empirical Bayes tuning","\n") } dat_ext = matrix(rep(1, nvar)) } else { #### If Z is provided: dimZ = dim(Z) nrowZ = ifelse(is.null(dimZ), length(Z), dimZ[1]) ncolZ = ifelse(is.null(dimZ), 1, dimZ[2]) if (nrowZ != nvar) { ## check the dimension of Z stop(paste("number of rows in Z (", nrow(Z), ") not equal to the number of columns in X (", nvar, ")", sep = "")) } else if (!is.matrix(Z)) { ## check is Z is a matrix Z = as.matrix(Z) dat_ext <- Z } else if (!(typeof(Z) %in% c("double", "integer"))) { stop("Z contains non-numeric values") } else if (all(apply(Z, 2, function(x) length(unique(x)) == 1) == TRUE)) { ## check if all rows in Z are the same warning(paste("All rows in Z are the same, this Z matrix is not useful, EB tuning will be performed to estimate a single tuning parameter","\n")) dat_ext = matrix(rep(1, nvar)) } else { dat_ext <- Z } if (message == TRUE){ cat(paste("Z provided, start estimating individual tuning parameters","\n")) } } # Standardize the Z and add an intercept in Z to stabilize the estimation # Append the intercept of the prior covariate coefficient dat_ext = sweep(dat_ext,2,colMeans(dat_ext)) dat_ext = cbind(1, dat_ext) drop(Z) nex = ncol(dat_ext) ## Check U if(!is.null(U)){ if (!is.matrix(U) & !is.data.frame(U) ) { stop("Covariate should be in the matrix or data frame format") } else { U = U } } ## Check c if (!is.numeric(c) | c >1 | c< 0) { stop("c should be a numerical number ranging from 0 to 1") } else { c = c } ## Check sigma.square if (is.null(sigma.square)) { sigma.square = estimateVariance(X, Y) } else if (!is.double(sigma.square) | is.infinite(sigma.square) | sigma.square <= 0) { stop("sigma square should be a positive finite number") } else { sigma.square = sigma.square } # check control object control <- do.call("xtune.control", control) control <- initialize_control(control, dat_ext) # core function if(family == "linear"){ fit <- xtune.fit(X = X, Y = Y, Z = dat_ext, U = U, c = c, epsilon = epsilon, sigma.square = sigma.square, alpha.est.init = control$alpha.est.init, maxstep = control$maxstep, maxstep_inner = control$maxstep_inner, margin = control$margin, margin_inner = control$margin_inner, compute.likelihood = control$compute.likelihood, verbosity = control$verbosity, standardize = control$standardize, intercept = control$intercept) } else if(family == "binary" | family == "multiclass"){ fit <- mxtune.fit(X = X, Y = Y, Z = dat_ext, U = U, c = c, epsilon = epsilon, alpha.est.init = control$alpha.est.init, max_s = control$max_s, maxstep = control$maxstep, maxstep_inner = control$maxstep_inner, margin_s = control$margin_s, margin = control$margin, margin_inner = control$margin_inner, compute.likelihood = control$compute.likelihood, verbosity = control$verbosity, standardize = control$standardize, intercept = control$intercept) } # Check status of model fit if (length(unique(fit$penalty.vector)) == 1) { fit$penalty.vector = rep(1,nvar) } fit$family = family return(structure(fit, class = "xtune")) } #' Control function for xtune fitting #' #' @description Control function for \code{\link{xtune}} fitting. #' @param alpha.est.init Initial values of alpha vector supplied to the algorithm. Alpha values are the hyper-parameters for the double exponential prior of regression coefficients, and it controls the prior variance of regression coefficients. Default is a vector of 0 with length p. #' @param max_s Maximum number of outer loop iterations for binary or multiclass outcomes. Default is 20. #' @param margin_s Convergence threshold of the outer loop for binary or multiclass outcomes. Default is 1e-5. #' @param maxstep Maximum number of iterations. Default is 100. #' @param margin Convergence threshold. Default is 1e-3. #' @param maxstep_inner Maximum number of iterations for the inner loop of the majorization-minimization algorithm. Default is 100. #' @param margin_inner Convergence threshold for the inner loop of the majorization-minimization algorithm. Default is 1e-3. #' @param compute.likelihood Should the function compute the marginal likelihood for hyper-parameters at each step of the update? Default is TRUE. #' @param verbosity Track algorithm update process? Default is FALSE. #' @param standardize Standardize X or not, same as the standardized option in \code{glmnet}. #' @param intercept Should intercept(s) be fitted (default=TRUE) or set to zero (FALSE), same as the intercept option in \code{glmnet}. #' @return A list of control objects after the checking. #' @export #' xtune.control <- function(alpha.est.init = NULL, max_s = 20 ,margin_s = 0.00001, maxstep = 100, margin = 0.001, maxstep_inner = 100, margin_inner = 0.001, compute.likelihood = FALSE, verbosity = FALSE, standardize = TRUE, intercept = TRUE) { if (max_s < 0) { stop("Error: max out loop step must be a postive integer") } if (margin_s < 0) { stop("Error: outer loop tolerance must be greater than 0") } if (maxstep < 0) { stop("Error: max out loop step must be a postive integer") } if (margin < 0) { stop("Error: outer loop tolerance must be greater than 0") } if (maxstep_inner < 0) { stop("Error: max inner loop step must be a postive integer") } if (margin_inner < 0) { stop("Error: inner loop tolerance must be greater than 0") } if (!is.logical(compute.likelihood)) { stop("Error: compute.likelihood should be either TRUE or FALSE") } if (!is.logical(verbosity)) { stop("Error: verbosity should be either TRUE or FALSE") } control_obj <- list(alpha.est.init = alpha.est.init, max_s = max_s, margin_s = margin_s, maxstep = maxstep, margin = margin, maxstep_inner = maxstep_inner, margin_inner = margin_inner, compute.likelihood = compute.likelihood, verbosity = verbosity, standardize = standardize, intercept = intercept) } initialize_control <- function(control_obj, ext) { if (is.null(control_obj$alpha.est.init) | all(apply(ext, 2, function(x) length(unique(x)) == 1) == TRUE)) { alpha.est.init = rep(0, ncol(ext)) } else if (length(control_obj$alpha.est.init) != ncol(ext)) { warning(cat(paste("number of elements in alpha initial values (", length(alpha.est.init), ") not equal to the number of columns of ext (", q, ")", ", alpha initial set to be all 0", sep = ""))) } else { alpha.est.init = control_obj$alpha.est.init } control_obj$alpha.est.init <- alpha.est.init return(control_obj) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/xtune.R
#' @import glmnet crayon selectiveInference #' @importFrom stats optim coef var predict xtune.fit <- function(X, Y, Z, U, c, epsilon, sigma.square, alpha.est.init, maxstep, margin, maxstep_inner, margin_inner, compute.likelihood, verbosity, standardize = standardize, intercept = intercept) { n = nrow(X) p = ncol(X) ##------------ Elastic-net regression ## Initialize alpha.old = alpha.est.init likelihood.score = c() s = 1 ## calculate alpha.max alpha.max = max(abs(colSums(X*as.vector(Y))))/ (c * n) ## start estimation cat(yellow$italic$bold("Start estimating alpha:\n")) while(s < maxstep){ # Given alpha, update theta lambda = exp(Z%*%alpha.old) gamma = 2/(lambda^2*c^2 + 2*lambda*(1-c)) Sigma_y = sigma.square * diag(n) + (t(t(X) * c(gamma))) %*% t(X) theta = colSums(X * solve(Sigma_y, X)) # Compute likelihood if (compute.likelihood == TRUE) { likelihood.score = c(likelihood.score, approx_likelihood.xtune(alpha.old, X, Y, Z, sigma.square, c)) } # Given theta, update alpha update.result <- update_alpha.xtune(X, Y, Z,c=c, alpha.old = alpha.old, alpha.max = alpha.max, epsilon = epsilon, sigma.square = sigma.square, theta = theta, maxstep_inner = maxstep_inner, margin_inner = margin_inner, verbosity = verbosity) alpha.new <- update.result$alpha.est # Check convergence if (sum(abs(alpha.new - alpha.old)) < margin) { cat(red$bold("Done!\n")) break } alpha.old <- alpha.new # Track iteration progress if (verbosity == TRUE) { cat(green$italic("#---"),green$bold("Outer loop Iteration",s,"Done"),green$italic("---#\n"),sep = "") } s <- s + 1 } tauEst = exp(Z%*%alpha.old) pen_vec = tauEst * sigma.square/n pen_vec[pen_vec>1e6] <- 1e6 if(is.null(U)) {pen_vec_cov = pen_vec} else {pen_vec_cov = c(pen_vec, rep(0,ncol(U)))} C = sum(pen_vec_cov)/p obj <- glmnet(cbind(X, U), Y, alpha = c,family="gaussian",lambda = C, penalty.factor = pen_vec_cov, standardize = standardize, intercept = intercept) cus.coef <- coef(obj,x=cbind(X, U),y=Y,alpha = c, exact=TRUE,s= C, penalty.factor = pen_vec_cov,standardize=standardize,intercept = intercept) return(list(model = obj, beta.est = cus.coef, penalty.vector = pen_vec_cov, lambda = C, alpha.est = alpha.old, n_iter = s - 1, sigma.square = sigma.square, likelihood.score = likelihood.score)) }
/scratch/gouwar.j/cran-all/cranData/xtune/R/xtune_fit.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----ex1---------------------------------------------------------------------- library(xtune) data("example") X <- example$X; Y <- example$Y; Z <- example$Z dim(X);dim(Z) ## ----dim---------------------------------------------------------------------- X[1:3,1:10] ## ----------------------------------------------------------------------------- Z[1:10,] ## ----fit1--------------------------------------------------------------------- fit.example1 <- xtune(X,Y,Z, family = "linear", c = 1) ## ----ex1uni------------------------------------------------------------------- unique(fit.example1$penalty.vector) ## ----ex2_data----------------------------------------------------------------- data(diet) head(diet$DietItems) head(diet$weightloss) ## ----ex2ex-------------------------------------------------------------------- head(diet$NuitritionFact) ## ----exfit-------------------------------------------------------------------- fit.diet = xtune(X = diet$DietItems,Y=diet$weightloss,Z = diet$NuitritionFact, family="binary", c = 0) ## ----indiv-------------------------------------------------------------------- fit.diet$penalty.vector ## ----ex3_data----------------------------------------------------------------- data(gene) gene$GeneExpression[1:3,1:5] gene$PreviousStudy[1:5,] ## ----multiclass--------------------------------------------------------------- data("example.multiclass") dim(example.multiclass$X); dim(example.multiclass$Y); dim(example.multiclass$Z) head(example.multiclass$X)[,1:5] head(example.multiclass$Y) head(example.multiclass$Z) ## ----------------------------------------------------------------------------- fit.multiclass = xtune(X = example.multiclass$X,Y=example.multiclass$Y,Z = example.multiclass$Z, U = example.multiclass$U, family = "multiclass", c = 0.5) # check the tuning parameter fit.multiclass$penalty.vector ## ----------------------------------------------------------------------------- pred.prob = predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U)) head(pred.prob) ## ----------------------------------------------------------------------------- pred.class <- predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U), type = "class") head(pred.class) ## ----------------------------------------------------------------------------- misclassification(pred.class,true = example.multiclass$Y) ## ----sp1---------------------------------------------------------------------- fit.eb <- xtune(X,Y, family = "linear", c = 0.5) ## ----sp2---------------------------------------------------------------------- Z_iden = diag(ncol(diet$DietItems)) fit.diet.identity = xtune(diet$DietItems,diet$weightloss,Z_iden, family = "binary", c = 0.5) ## ----sp22--------------------------------------------------------------------- fit.diet.identity$penalty.vector
/scratch/gouwar.j/cran-all/cranData/xtune/inst/doc/Tutorials_for_xtune.R
--- title: "Getting started with `xtune`" author: "Jingxuan He and Chubing Zeng" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Tutorials_for_xtune} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ### Purpose of this vignette This vignette is a tutorial on how to use the `xtune` package to fit feature-specific regularized regression models based on external information. In this tutorial the following points are going to be viewed: * The overall idea of `xtune` model * Three examples of external information Z * How to fit the model * Two special cases of Z ### `xtune` Overview The main usage of `xtune` is to tune multiple shrinkage parameters in regularized regressions (Lasso, Ridge, and Elastic-net), based on external information. The classical penalized regression uses a single penalty parameter $\lambda$ that applies equally to all regression coefficients to control the amount of regularization in the model. And the single penalty parameter tuning is typically performed using cross-validation. Here we apply an individual shrinkage parameter $\lambda_j$ to each regression coefficient $\beta_j$. And the vector of shrinkage parameters $\lambda s = (\lambda_1,...,\lambda_p)$ is guided by external information $Z$. In specific, $\lambda$s is modeled as a log-linear function of $Z$. Better prediction accuracy for penalized regression models may be achieved by allowing individual shrinkage for each regression coefficients based on external information. To tune the differential shrinkage parameter vector $\lambda s = (\lambda_1,...,\lambda_p)$, we employ an Empirical Bayes approach by specifying Elastic-net to their random-effect formulation. Once the tuning parameters $\lambda$s are estimated, and therefore the penalties known, the regression coefficients are obtained using the `glmnet` package. The response variable can be either quantitative or categorical. Utilities for carrying out post-fitting summary and prediction are also provided. ### Examples Here, we four simulated examples to illustrate the usage and syntax of `xtune`. The first example gives users a general sense of the data structure and model fitting process. The second and third examples use simulated data in concrete scenarios to illustrate the usage of the package. In the second example `diet`, we provide simulated data to mimic the dietary example described in this paper: S. Witte, John & Greenland, Sander & W. Haile, Robert & L. Bird, Cristy. (1994). Hierarchical Regression Analysis Applied to a Study of Multiple Dietary Exposures and Breast Cancer. Epidemiology (Cambridge, Mass.). 5. 612-21. 10.1097/00001648-199411000-00009. In the third example `gene`, we provide simulated data to mimic the bone density data published in the European Bioinformatics Institute (EMBL-EBI) ArrayExpress repository, ID: E-MEXP-1618. And in the fourth example, we simulated data with multicategorical outcomes with three levels to provide the multi-classification example using `xtune`. #### General Example In the first example, $Y$ is a $n = 100$-dimensional continuous observed outcome vector, $X$ is matrix of $p$ potential predictors observed on the $n$ observations, and $Z$ is a set of $q = 4$ external features available for the $p = 300$ predictors. ```{r ex1} library(xtune) data("example") X <- example$X; Y <- example$Y; Z <- example$Z dim(X);dim(Z) ``` Each column of Z contains information about the predictors in design matrix X. The number of rows in Z equals to the number of predictors in X. ```{r dim} X[1:3,1:10] ``` The external information is encoded as follows: ```{r} Z[1:10,] ``` Here, each variable in Z is a binary variable. $Z_{jk}$ indicates if $Predictor_j$ has $ExternalVariable_k$ or not. This Z is an example of (non-overlapping) grouping of predictors. Predictor 1 and 2 belongs to group 1; predictor 3 and 4 belongs to group 2; predictor 5 and 6 belongs to group 3, and the rest of the predictors belongs to group 4. To fit a differential-shrinkage lasso model to this data: ```{r fit1} fit.example1 <- xtune(X,Y,Z, family = "linear", c = 1) ``` Here, we specify the family of the model using the linear response and the LASSO type of penalty by assign $c = 1$. The individual penalty parameters are returned by ``` fit.example1$penalty.vector ``` In this example, predictors in each group get different estimated penalty parameters. ```{r ex1uni} unique(fit.example1$penalty.vector) ``` Coefficient estimates and predicted values and can be obtained via `predict` and `coef`: ``` coef_xtune(fit.example1) predict_xtune(fit.example1, newX = X) ``` The `mse` function can be used to get the mean square error (MSE) between prediction values and true values. ``` mse(predict(fit.example1, newX = X), Y) ``` #### Dietary example Suppose we want to predict a person's weight loss (binary outcome) using his/her weekly dietary intake. Our external information Z could incorporate information about the levels of relevant food constituents in the dietary items. ```{r ex2_data} data(diet) head(diet$DietItems) head(diet$weightloss) ``` The external information Z in this example is: ```{r ex2ex} head(diet$NuitritionFact) ``` In this example, Z is not a grouping of the predictors. The idea is that the nutrition facts about the dietary items might give us some information on the importance of each predictor in the model. Similar to the previous example, the xtune model could be fit by: ```{r exfit} fit.diet = xtune(X = diet$DietItems,Y=diet$weightloss,Z = diet$NuitritionFact, family="binary", c = 0) ``` Here, we use the Ridge model by specifying $c = 0$. Each dietary predictor is estimated an individual tuning parameter based on their nutrition fact. ```{r indiv} fit.diet$penalty.vector ``` To make prediction using the trained model ``` predict_xtune(fit.diet,newX = diet$DietItems) ``` The above code returns the predicted probabilities (scores). To make a class prediction, use the `type = "class"` option. ``` pred_class <- predict_xtune(fit.diet,newX = diet$DietItems,type = "class") ``` The `misclassification()` function can be used to extract the misclassification rate. The prediction AUC can be calculated using the auc() function from the AUC package. ``` misclassification(pred_class,true = diet$weightloss) ``` #### Gene expression data example The `gene` data contains simulated gene expression data. The dimension of data is $50\times 200$. The outcome Y is continuous (bone mineral density). The external information is four previous study results that identify the biological importance of genes. For example $Z_{jk}$ means whether $gene_j$ is identified to be biologically important in previous study $k$ result. $Z_{jk} = 1$ means that gene $j$ is identified by previous study $k$ result and $Z_{jk} = 0$ means that gene $j$ is not identified to be important by previous study $k$ result. ```{r ex3_data} data(gene) gene$GeneExpression[1:3,1:5] gene$PreviousStudy[1:5,] ``` A gene can be identified to be important by several previous study results, therefore the external information Z in this example can be seen as an overlapping group of variables. Model fitting: ``` fit.gene = xtune(X = gene$GeneExpression,Y=gene$bonedensity,Z = gene$PreviousStudy, family = "linear", c = 0.5) ``` We use the Elastic-net model by specifying $c = 0.5$ (can be any numerical value from 0 to 1). The rest of the steps are the same as the previous two examples. #### Multi-classification data example ```{r multiclass} data("example.multiclass") dim(example.multiclass$X); dim(example.multiclass$Y); dim(example.multiclass$Z) head(example.multiclass$X)[,1:5] head(example.multiclass$Y) head(example.multiclass$Z) ``` Model fitting: ```{r} fit.multiclass = xtune(X = example.multiclass$X,Y=example.multiclass$Y,Z = example.multiclass$Z, U = example.multiclass$U, family = "multiclass", c = 0.5) # check the tuning parameter fit.multiclass$penalty.vector ``` To make prediction using the trained model: ```{r} pred.prob = predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U)) head(pred.prob) ``` The above code returns the predicted probabilities (scores) for each class. To make a class prediction, specify the argument `type = "class"`. ```{r} pred.class <- predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U), type = "class") head(pred.class) ``` The `misclassification()` function can be used to extract the misclassification rate. The multiclass AUC can be calculated using the `multiclass.roc` function from the `pROC` package. ```{r} misclassification(pred.class,true = example.multiclass$Y) ``` ### Two special cases #### No external information Z If you just want to tune a single penalty parameter using empirical Bayes tuning, simply do not provide Z in the `xtune()` function. If no external information Z is provided, the function will perform empirical Bayes tuning to choose the single penalty parameter in penalized regression, as an alternative to cross-validation. For example ```{r sp1} fit.eb <- xtune(X,Y, family = "linear", c = 0.5) ``` The estimated tuning parameter is: ``` fit.eb$lambda ``` #### Z as an identity matrix If you provide an identity matrix as external information Z to `xtune()`, the function will estimate a separate tuning parameter $\lambda_j$ for each regression coefficient $\beta_j$. Note that this is not advised when the number of predictors $p$ is very large. Using the dietary example, the following code would estimate a separate penalty parameter for each coefficient. ```{r sp2} Z_iden = diag(ncol(diet$DietItems)) fit.diet.identity = xtune(diet$DietItems,diet$weightloss,Z_iden, family = "binary", c = 0.5) ``` ```{r sp22} fit.diet.identity$penalty.vector ``` A predictor is excluded from the model (regression coefficient equals to zero) if its corresponding penalty parameter is estimated to be infinity. ### Conclusion We presented the main usage of `xtune` package. For more details about each function, please go check the package documentation. If you would like to give us feedback or report issue, please tell us on [Github](https://github.com/JingxuanH/xtune).
/scratch/gouwar.j/cran-all/cranData/xtune/inst/doc/Tutorials_for_xtune.Rmd
--- title: "Getting started with `xtune`" author: "Jingxuan He and Chubing Zeng" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Tutorials_for_xtune} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ### Purpose of this vignette This vignette is a tutorial on how to use the `xtune` package to fit feature-specific regularized regression models based on external information. In this tutorial the following points are going to be viewed: * The overall idea of `xtune` model * Three examples of external information Z * How to fit the model * Two special cases of Z ### `xtune` Overview The main usage of `xtune` is to tune multiple shrinkage parameters in regularized regressions (Lasso, Ridge, and Elastic-net), based on external information. The classical penalized regression uses a single penalty parameter $\lambda$ that applies equally to all regression coefficients to control the amount of regularization in the model. And the single penalty parameter tuning is typically performed using cross-validation. Here we apply an individual shrinkage parameter $\lambda_j$ to each regression coefficient $\beta_j$. And the vector of shrinkage parameters $\lambda s = (\lambda_1,...,\lambda_p)$ is guided by external information $Z$. In specific, $\lambda$s is modeled as a log-linear function of $Z$. Better prediction accuracy for penalized regression models may be achieved by allowing individual shrinkage for each regression coefficients based on external information. To tune the differential shrinkage parameter vector $\lambda s = (\lambda_1,...,\lambda_p)$, we employ an Empirical Bayes approach by specifying Elastic-net to their random-effect formulation. Once the tuning parameters $\lambda$s are estimated, and therefore the penalties known, the regression coefficients are obtained using the `glmnet` package. The response variable can be either quantitative or categorical. Utilities for carrying out post-fitting summary and prediction are also provided. ### Examples Here, we four simulated examples to illustrate the usage and syntax of `xtune`. The first example gives users a general sense of the data structure and model fitting process. The second and third examples use simulated data in concrete scenarios to illustrate the usage of the package. In the second example `diet`, we provide simulated data to mimic the dietary example described in this paper: S. Witte, John & Greenland, Sander & W. Haile, Robert & L. Bird, Cristy. (1994). Hierarchical Regression Analysis Applied to a Study of Multiple Dietary Exposures and Breast Cancer. Epidemiology (Cambridge, Mass.). 5. 612-21. 10.1097/00001648-199411000-00009. In the third example `gene`, we provide simulated data to mimic the bone density data published in the European Bioinformatics Institute (EMBL-EBI) ArrayExpress repository, ID: E-MEXP-1618. And in the fourth example, we simulated data with multicategorical outcomes with three levels to provide the multi-classification example using `xtune`. #### General Example In the first example, $Y$ is a $n = 100$-dimensional continuous observed outcome vector, $X$ is matrix of $p$ potential predictors observed on the $n$ observations, and $Z$ is a set of $q = 4$ external features available for the $p = 300$ predictors. ```{r ex1} library(xtune) data("example") X <- example$X; Y <- example$Y; Z <- example$Z dim(X);dim(Z) ``` Each column of Z contains information about the predictors in design matrix X. The number of rows in Z equals to the number of predictors in X. ```{r dim} X[1:3,1:10] ``` The external information is encoded as follows: ```{r} Z[1:10,] ``` Here, each variable in Z is a binary variable. $Z_{jk}$ indicates if $Predictor_j$ has $ExternalVariable_k$ or not. This Z is an example of (non-overlapping) grouping of predictors. Predictor 1 and 2 belongs to group 1; predictor 3 and 4 belongs to group 2; predictor 5 and 6 belongs to group 3, and the rest of the predictors belongs to group 4. To fit a differential-shrinkage lasso model to this data: ```{r fit1} fit.example1 <- xtune(X,Y,Z, family = "linear", c = 1) ``` Here, we specify the family of the model using the linear response and the LASSO type of penalty by assign $c = 1$. The individual penalty parameters are returned by ``` fit.example1$penalty.vector ``` In this example, predictors in each group get different estimated penalty parameters. ```{r ex1uni} unique(fit.example1$penalty.vector) ``` Coefficient estimates and predicted values and can be obtained via `predict` and `coef`: ``` coef_xtune(fit.example1) predict_xtune(fit.example1, newX = X) ``` The `mse` function can be used to get the mean square error (MSE) between prediction values and true values. ``` mse(predict(fit.example1, newX = X), Y) ``` #### Dietary example Suppose we want to predict a person's weight loss (binary outcome) using his/her weekly dietary intake. Our external information Z could incorporate information about the levels of relevant food constituents in the dietary items. ```{r ex2_data} data(diet) head(diet$DietItems) head(diet$weightloss) ``` The external information Z in this example is: ```{r ex2ex} head(diet$NuitritionFact) ``` In this example, Z is not a grouping of the predictors. The idea is that the nutrition facts about the dietary items might give us some information on the importance of each predictor in the model. Similar to the previous example, the xtune model could be fit by: ```{r exfit} fit.diet = xtune(X = diet$DietItems,Y=diet$weightloss,Z = diet$NuitritionFact, family="binary", c = 0) ``` Here, we use the Ridge model by specifying $c = 0$. Each dietary predictor is estimated an individual tuning parameter based on their nutrition fact. ```{r indiv} fit.diet$penalty.vector ``` To make prediction using the trained model ``` predict_xtune(fit.diet,newX = diet$DietItems) ``` The above code returns the predicted probabilities (scores). To make a class prediction, use the `type = "class"` option. ``` pred_class <- predict_xtune(fit.diet,newX = diet$DietItems,type = "class") ``` The `misclassification()` function can be used to extract the misclassification rate. The prediction AUC can be calculated using the auc() function from the AUC package. ``` misclassification(pred_class,true = diet$weightloss) ``` #### Gene expression data example The `gene` data contains simulated gene expression data. The dimension of data is $50\times 200$. The outcome Y is continuous (bone mineral density). The external information is four previous study results that identify the biological importance of genes. For example $Z_{jk}$ means whether $gene_j$ is identified to be biologically important in previous study $k$ result. $Z_{jk} = 1$ means that gene $j$ is identified by previous study $k$ result and $Z_{jk} = 0$ means that gene $j$ is not identified to be important by previous study $k$ result. ```{r ex3_data} data(gene) gene$GeneExpression[1:3,1:5] gene$PreviousStudy[1:5,] ``` A gene can be identified to be important by several previous study results, therefore the external information Z in this example can be seen as an overlapping group of variables. Model fitting: ``` fit.gene = xtune(X = gene$GeneExpression,Y=gene$bonedensity,Z = gene$PreviousStudy, family = "linear", c = 0.5) ``` We use the Elastic-net model by specifying $c = 0.5$ (can be any numerical value from 0 to 1). The rest of the steps are the same as the previous two examples. #### Multi-classification data example ```{r multiclass} data("example.multiclass") dim(example.multiclass$X); dim(example.multiclass$Y); dim(example.multiclass$Z) head(example.multiclass$X)[,1:5] head(example.multiclass$Y) head(example.multiclass$Z) ``` Model fitting: ```{r} fit.multiclass = xtune(X = example.multiclass$X,Y=example.multiclass$Y,Z = example.multiclass$Z, U = example.multiclass$U, family = "multiclass", c = 0.5) # check the tuning parameter fit.multiclass$penalty.vector ``` To make prediction using the trained model: ```{r} pred.prob = predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U)) head(pred.prob) ``` The above code returns the predicted probabilities (scores) for each class. To make a class prediction, specify the argument `type = "class"`. ```{r} pred.class <- predict_xtune(fit.multiclass,newX = cbind(example.multiclass$X, example.multiclass$U), type = "class") head(pred.class) ``` The `misclassification()` function can be used to extract the misclassification rate. The multiclass AUC can be calculated using the `multiclass.roc` function from the `pROC` package. ```{r} misclassification(pred.class,true = example.multiclass$Y) ``` ### Two special cases #### No external information Z If you just want to tune a single penalty parameter using empirical Bayes tuning, simply do not provide Z in the `xtune()` function. If no external information Z is provided, the function will perform empirical Bayes tuning to choose the single penalty parameter in penalized regression, as an alternative to cross-validation. For example ```{r sp1} fit.eb <- xtune(X,Y, family = "linear", c = 0.5) ``` The estimated tuning parameter is: ``` fit.eb$lambda ``` #### Z as an identity matrix If you provide an identity matrix as external information Z to `xtune()`, the function will estimate a separate tuning parameter $\lambda_j$ for each regression coefficient $\beta_j$. Note that this is not advised when the number of predictors $p$ is very large. Using the dietary example, the following code would estimate a separate penalty parameter for each coefficient. ```{r sp2} Z_iden = diag(ncol(diet$DietItems)) fit.diet.identity = xtune(diet$DietItems,diet$weightloss,Z_iden, family = "binary", c = 0.5) ``` ```{r sp22} fit.diet.identity$penalty.vector ``` A predictor is excluded from the model (regression coefficient equals to zero) if its corresponding penalty parameter is estimated to be infinity. ### Conclusion We presented the main usage of `xtune` package. For more details about each function, please go check the package documentation. If you would like to give us feedback or report issue, please tell us on [Github](https://github.com/JingxuanH/xtune).
/scratch/gouwar.j/cran-all/cranData/xtune/vignettes/Tutorials_for_xtune.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 html_decode_rcpp_single <- function(s) { .Call(`_xutils_html_decode_rcpp_single`, s) }
/scratch/gouwar.j/cran-all/cranData/xutils/R/RcppExports.R
#' Decode a character vector #' #' This function is a wrapper around existing C++ code on decoding HTML entities. #' The original C++ code is given by Christoph. Please refer to the answer on SO #' [here](https://stackoverflow.com/a/1082191/10437891). #' #' @param str A character vector #' @return Decoded character vector #' @examples #' html_decode(c("&amp;", "&euro;")) #' @export html_decode <- function(str) { strlong <- paste0(str, collapse = "#_|") parsed <- html_decode_rcpp_single(strlong) strsplit(parsed, "#_|", fixed = TRUE)[[1]] }
/scratch/gouwar.j/cran-all/cranData/xutils/R/html_decode.R
## usethis namespace: start #' @importFrom Rcpp sourceCpp ## usethis namespace: end NULL ## usethis namespace: start #' @useDynLib xutils, .registration = TRUE ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/xutils/R/xutils-package.R
.onUnload <- function (libpath) { library.dynam.unload("xutils", libpath) }
/scratch/gouwar.j/cran-all/cranData/xutils/R/zzz.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(xutils) ## ----------------------------------------------------------------------------- strings <- c("abcd", "&amp; &apos; &gt;", "&amp;", "&euro; &lt;") html_decode(strings) ## ----------------------------------------------------------------------------- unescape_html2 <- function(str){ html <- paste0("<x>", paste0(str, collapse = "#_|"), "</x>") parsed <- xml2::xml_text(xml2::read_html(html)) strsplit(parsed, "#_|", fixed = TRUE)[[1]] } ## ----------------------------------------------------------------------------- bench::mark( html_decode(strings), unescape_html2(strings), textutils::HTMLdecode(strings) )
/scratch/gouwar.j/cran-all/cranData/xutils/inst/doc/Introduction.R
--- title: "Introduction" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This is a package where I collected some of the function I have used when dealing with data. ```{r setup} library(xutils) ``` # Text-related Functions ## `html_decode` Currently, there is only one function: `html_decode` which will replace the HTML entities like `&amp;` into their original form `&`. This function is a thin-wrapper of C++ code provided by **Christoph** on [Stack Overflow](https://stackoverflow.com/a/1082191/10437891). ### Example An example would be ```{r} strings <- c("abcd", "&amp; &apos; &gt;", "&amp;", "&euro; &lt;") html_decode(strings) ``` It works very well! ### Comparison with Existing Solutions To the best of my knowledge, there are already several solutions to this problem, and why do I need to wrap up a new function to do this? Because of performance. First of all, there is an existing package `textutils` that contains lots of functions dealing with data. The one of our interest is `HTMLdecode`. Second, there is a function by SO user **Stibu** [here](https://stackoverflow.com/questions/5060076/convert-html-character-entity-encoding-in-r/65909574#65909574) that uses `xml2` package. And the function is: ```{r} unescape_html2 <- function(str){ html <- paste0("<x>", paste0(str, collapse = "#_|"), "</x>") parsed <- xml2::xml_text(xml2::read_html(html)) strsplit(parsed, "#_|", fixed = TRUE)[[1]] } ``` Third, I took the code from **Christoph** ([here](https://stackoverflow.com/a/1082191/10437891)) and wrote a R wrapper for the C function. This function is `xutils::html_decode`. Now, let's test the performance and I use `bench` package here. ```{r} bench::mark( html_decode(strings), unescape_html2(strings), textutils::HTMLdecode(strings) ) ``` Clearly, the speed of `html_decode` function is unparalleled. **Note**: When testing the results, I discovered a bug in `textutils::HTMLdecode` and reported it [here](https://github.com/enricoschumann/textutils/issues/3). The maintainer fixed it immediately. As of this writing (Feb. 16, 2021), the development version of `textutils` has this bug fixed, but the CRAN version may not. This means that if you test the performance yourself with a previous version of `textutils`, you may run into error and installing the development version will solve for it.
/scratch/gouwar.j/cran-all/cranData/xutils/inst/doc/Introduction.Rmd
--- title: "Introduction" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This is a package where I collected some of the function I have used when dealing with data. ```{r setup} library(xutils) ``` # Text-related Functions ## `html_decode` Currently, there is only one function: `html_decode` which will replace the HTML entities like `&amp;` into their original form `&`. This function is a thin-wrapper of C++ code provided by **Christoph** on [Stack Overflow](https://stackoverflow.com/a/1082191/10437891). ### Example An example would be ```{r} strings <- c("abcd", "&amp; &apos; &gt;", "&amp;", "&euro; &lt;") html_decode(strings) ``` It works very well! ### Comparison with Existing Solutions To the best of my knowledge, there are already several solutions to this problem, and why do I need to wrap up a new function to do this? Because of performance. First of all, there is an existing package `textutils` that contains lots of functions dealing with data. The one of our interest is `HTMLdecode`. Second, there is a function by SO user **Stibu** [here](https://stackoverflow.com/questions/5060076/convert-html-character-entity-encoding-in-r/65909574#65909574) that uses `xml2` package. And the function is: ```{r} unescape_html2 <- function(str){ html <- paste0("<x>", paste0(str, collapse = "#_|"), "</x>") parsed <- xml2::xml_text(xml2::read_html(html)) strsplit(parsed, "#_|", fixed = TRUE)[[1]] } ``` Third, I took the code from **Christoph** ([here](https://stackoverflow.com/a/1082191/10437891)) and wrote a R wrapper for the C function. This function is `xutils::html_decode`. Now, let's test the performance and I use `bench` package here. ```{r} bench::mark( html_decode(strings), unescape_html2(strings), textutils::HTMLdecode(strings) ) ``` Clearly, the speed of `html_decode` function is unparalleled. **Note**: When testing the results, I discovered a bug in `textutils::HTMLdecode` and reported it [here](https://github.com/enricoschumann/textutils/issues/3). The maintainer fixed it immediately. As of this writing (Feb. 16, 2021), the development version of `textutils` has this bug fixed, but the CRAN version may not. This means that if you test the performance yourself with a previous version of `textutils`, you may run into error and installing the development version will solve for it.
/scratch/gouwar.j/cran-all/cranData/xutils/vignettes/Introduction.Rmd
#' p-value computation for XWFs #' #' Randomization method to compute p-values for an optimized extrema-weighted features generalized additive model fit. #' #' @param GAMobject The GAMobject returned by \code{\link{xwfGridsearch}} #' @param xx List of function for which to compute the XWFs #' @param t Matrix containing the times at which the functions xx were measured: Element (i,j) contains the time of the j-th measurement of the i-th function. #' @param n.i Vector containing the number of measurements for each function. The first n.i[i] elements of the i-th row of t should not be NA. #' @param psi.list List of predefined local features which are functions of a function (first argument) and a measurement time (second argument) #' @param F CDF of the values of the functions xx. Ignored if weighting function w is not the default. #' @param z Optional matrix with covariates to be included as linear predictors in the generalized additive model #' @param w Weighting function. The default is the one used in the original paper. See the default for what the roles of its 3 arguments are. #' @param n.boot Number for randomizations used to obtain the p-values. The resolution of the p-values is 1/n.boot #' @param progressbar Boolean specifying whether a progress bar indicating which randomizations have been completed should be displayed. #' #' @return Named vector with p-values #' #' @examples #' # Data simulation similar to Section 3.2 of the paper #' #' # Sample size #' n <- 100 #' #' # Length of trajectories #' n.i <- rep(5, n) #' max.n.i <- max(n.i) #' #' # Times #' t <- matrix(NA_integer_, nrow = n, ncol = max.n.i) #' for(i in 1:n) t[i, 1:n.i[i]] <- 1:n.i[i] #' #' #' # Sample periods #' phi <- runif(n = n, min = 1, max = 10) #' #' # Sample offsets #' m <- 10*runif(n = n) #' #' # Blood pressure measurements #' x <- t #' for(i in 1:n) x[i, 1:n.i[i]] <- sin(phi[i] * 2*pi/max.n.i * t[i, 1:n.i[i]]) + m[i] #' #' # Matrix with covariates z #' q <- 2 # Number of covariates #' z <- matrix(rnorm(n = n*q), nrow = n, ncol = q) #' #' # Generate outcomes #' temp <- phi*min(m, 7) #' temp <- 40*temp #' prob <- 1/(1+exp( 2*( median(temp)-temp ) )) #' y <- rbinom(n = n, size = 1, prob = prob) #' #' xx <- list() #' for(i in 1:n) xx[[i]] <- approxfun(x = t[i,1:n.i[i]], y = x[i,1:n.i[i]], rule = 2) #' #' # Estimate f #' weights <- matrix(1/n.i, ncol = max.n.i, nrow = n)[!is.na(t)] #' f <- density( #' x = t(sapply(X = 1:n, FUN = function(i) c(xx[[i]](t[i,1:n.i[i]]), rep(NA, max.n.i-n.i[i])))), #' weights = weights/sum(weights), #' na.rm = T #' ) #' #' # Define CDF of f, F #' CDF <- c(0) #' for(i in 2:length(f$x)) CDF[i] <- CDF[i-1]+(f$x[i]-f$x[i-1])*(f$y[i]+f$y[i-1])/2 #' F <- approxfun(x = f$x, y = CDF/max(CDF), yleft = 0, yright = 1) #' #' psi <- list( #' function(x, t) abs(x(t)-x(t-1)) #' ) #' #' XWFresult <- xwfGridsearch(y = y, xx = xx, t = t, n.i = n.i, psi.list = psi, F = F, z = z) #' #' \donttest{XWFpValues( #' GAMobject = XWFresult$GAMobject, #' xx = xx, #' t = t, #' n.i = n.i, #' psi.list = psi, #' F = F, #' z = z, #' n.boot = 3 #' )} #' #' @importFrom utils txtProgressBar setTxtProgressBar #' #' @export XWFpValues <- function(GAMobject, xx, t, n.i, psi.list = NULL, F, z = NULL, w = function(t, i, b, left) ifelse(left, min(1, (1-F(xx[[i]](t)))/(1-b)), min(1, F(xx[[i]](t))/b)), n.boot = 100, progressbar = TRUE) { if(is.null(psi.list)) { warning("'psi.list' is not specified. Therefore using default.psi(). Make sure psi.list are the same as used to obtain 'GAMobject' for the p-valus to be correct.") psi.list <- default_psi() } y <- GAMobject$model[,1] n.p <- length(GAMobject$model) pValMat <- matrix(NA_real_, nrow = n.boot, ncol = n.p) if(progressbar) pb <- txtProgressBar(max = n.boot, style = 3) for(s in 1:n.boot) { # We simply randomize y to get bootstrap samples temp <- tryCatch( xwfGridsearch(y = sample(y), xx = xx, t = t, n.i = n.i, psi.list = psi.list, F = F, z = z, w = w, progressbar = FALSE)$GAMobject, error = function(e) { cat("ERROR :",conditionMessage(e), "\n") return(NA) } ) if(!is.na(temp[1])) { temp <- c(summary(temp)$p.pv, summary(temp)$s.pv) if(n.p == length(temp)) pValMat[s, ] <- temp # This check on 'temp' is here to ensure 'xwfGridsearch did not accidentially return NA } if(progressbar) setTxtProgressBar(pb, s) } if(progressbar) close(pb) pValues <- rep(NA_real_, n.p) names(pValues) <- c(names(summary(GAMobject)$p.pv), rownames(summary(GAMobject)$s.table)) temp.p <- c(summary(GAMobject)$p.pv, summary(GAMobject)$s.pv) for(s in 1:n.p) { temp <- temp.p[s] >= pValMat[, s] pValues[s] <- (1+sum(temp, na.rm = TRUE))/(1+sum(!is.na(temp))) } return(pValues) }
/scratch/gouwar.j/cran-all/cranData/xwf/R/XWFpValues.R
#' Default psi list #' #' List with the same local feature functions psi as in the original paper #' #' @return List with 4 different local features psi #' #' @examples #' default_psi() #' #' @export default_psi <- function() list( function(x, t) rep(1, length(t)), function(x, t) x(t), function(x, t) pmax(x(t)-x(t-1), 0), function(x, t) -pmin(x(t)-x(t-1), 0) )
/scratch/gouwar.j/cran-all/cranData/xwf/R/default_psi.R
#' Compute XWFs #' #' Compute extrema-weighted features based on functions, predefined local features, and weighting functions #' #' @param xx List of function for which to compute the XWFs #' @param t Matrix containing the times at which the functions xx were measured: Element (i,j) contains the time of the j-th measurement of the i-th function. #' @param n.i Vector containing the number of measurements for each function. The first n.i[i] elements of the i-th row of t should not be NA. #' @param psi Predefined local feature which is a function of a function (first argument) and a measurement time (second argument) #' @param w Weighting function. The default is the one used in the original paper. #' @param b Parameter of the weighting function. See original paper for details. Ignored if weighting function w is not the default. #' @param F CDF of the values of the functions xx. Ignored if weighting function w is not the default. #' @param t.min Vector with time of first measurement for each function. Computed from t if omitted but providing it saves computational cost. #' @param t.max Analogous to t.min but now the time of the last measurement. #' @param t.range Vector with differences between t.max and t.min. Can be supplied to avoid recomputation. #' @param rel.shift Optional relative reduction of the integration range to avoid instabilities at the end of the integration ranges. Set to 0 if no such correction is desired. #' @param left Boolean specifying whether the left (TRUE) or right (FALSE) extrema-weighted features should be computed: Left and right refer to the weighting function. Ignored if weighting function w is not the default. #' #' @return Vector containing the extrema-weighted features obtained by numerical integration for each of the functions. #' #' @examples #' xwf( #' xx = list(function(t) t), #' t = (1:10)/10, #' n.i = 10, #' psi = function(x, t) x(t), #' b = .2, #' F = function(x) x #' ) #' #' @importFrom stats integrate #' #' @export xwf <- function(xx, t, n.i, psi, w = function(t, i) ifelse(left, min(1, (1-F(xx[[i]](t)))/(1-b)), min(1, F(xx[[i]](t))/b)), b = .5, F = NULL, t.min = NULL, t.max = NULL, t.range = NULL, rel.shift = .001, left = TRUE) { # This R script contains a function that computes Extrema Weighted Features (XWF) if(!is.null(F) &!is.function(F)) stop("marginal CDF 'F' is not specified as a function") if(!is.function(psi)) stop("local feature 'psi' is not specified as a function") if(!is.function(xx[[1]])) stop("trajectories 'xx' is not specified as a list of functions") n <- length(xx) if(length(n.i) == 1) n.i <- rep(n.i, n) # Compute t.min, t.max, and t.range if they are given. if(is.null(dim(t))) { if(is.null(t.min)) t.min <- min(t, na.rm = T) if(is.null(t.max)) t.max <- max(t, na.rm = T) } else { if(is.null(t.min)) t.min <- apply(X = t, MARGIN = 1, FUN = min, na.rm = T) if(is.null(t.max)) t.max <- apply(X = t, MARGIN = 1, FUN = max, na.rm = T) } if(is.null(t.range)) t.range <- t.max-t.min # Define the integral for the XWFs shift <- rel.shift*t.range # The lower and upper bound are shifted slightly inwards to prevent problems due to psi_j(x, t) not being properly defines, for instance at the boundaries. # Return the vector with XWFs return(Vectorize( FUN = function(i) integrate(f = function(t) w(t, i)*psi(xx[[i]], t), lower = t.min[i]+shift[i], upper = t.max[i]-shift[i], subdivisions = 100, rel.tol = .05, abs.tol = .05, stop.on.error = FALSE)$value/t.range[i] )(1:n)) }
/scratch/gouwar.j/cran-all/cranData/xwf/R/xwf.R
#' Evaluate the GAM #' #' Evaluate the generalized additive model for a set of computed extrema-weighted features #' #' @param wL Matrix with left extrema-weighted features #' @param wR Matrix with right extrema-weighted features #' @param y Binary vector with outcomes #' @param z Optional matrix z with extra, linear predictors #' #' @examples #' xwf:::xwfGAM(wL = rep(1:45, 10), wR = rep(1:90, 5), y = c(rep(0:1, 225))) #' #' @importFrom mgcv gam xwfGAM <- function(wL, wR, y, z = NULL) { p <- ncol(wL) if(is.null(p)) p <- 1 if(!is.null(z)) { q <- ncol(z) if(is.null(q)) q <- 1 } eval(parse(text = paste0( ifelse(is.null(z), "mgcv::gam(y ~ 1", ifelse(q == 1, "mgcv::gam(y ~ s(z)", paste0(c("mgcv::gam(y ~ s(z[,1])", sapply(X = 2:q, FUN = function(j) paste0("+s(z[,", j, "])"))), collapse = '') ) ), ifelse(p == 1, "+s(wL)+s(wR)", paste0(sapply(X = 1:p, FUN = function(j) paste0("+s(wL[,", j, "])+s(wR[,", j, "])")), collapse = '') ), ", family = binomial(link = 'logit'))" ))) }
/scratch/gouwar.j/cran-all/cranData/xwf/R/xwfGAM.R
#' Adaptive grid search #' #' Adaptive grid search to optimize the weighting functions in the extrema-weighted features. #' #' @param y Vector with binary outcomes data #' @param xx List of functions for which to compute the XWFs #' @param t Matrix containing the times at which the functions xx were measured: Element (i,j) contains the time of the j-th measurement of the i-th function. #' @param n.i Vector containing the number of measurements for each function. The first n.i[i] elements of the i-th row of t should not be NA. #' @param psi.list List of predefined local features which are functions of a function (first argument) and a measurement time (second argument) #' @param F CDF of the values of the functions xx. Ignored if weighting function w is not the default. #' @param z Optional matrix with covariates to be included as linear predictors in the generalized additive model #' @param w Weighting function. The default is the one used in the original paper. See the default for what the roles of its 3 arguments are. #' @param iter Number of levels in the adaptive grid search. The resolution in b obtained is 2^{-1-iter}. #' @param rel.shift Optional relative reduction of the integration range to avoid instabilities at the end of the integration ranges. Set to 0 if no such correction is desired. #' @param progressbar Boolean specifying whether a progress bar indicating what level of the adaptive grid has been completed should be displayed. #' #' @return List containing the final XWFs (wL and wR), the parameters for the optimal weighting functions (b.left and b.right), and the gmcv::gamObject corresponding to the final optimal generalized additive model fit. #' #' @examples #' # Data simulation similar to Section 3.2 of the paper #' #' # Sample size #' n <- 100 #' #' # Length of trajectories #' n.i <- rep(5, n) #' max.n.i <- max(n.i) #' #' # Times #' t <- matrix(NA_integer_, nrow = n, ncol = max.n.i) #' for(i in 1:n) t[i, 1:n.i[i]] <- 1:n.i[i] #' #' #' # Sample periods #' phi <- runif(n = n, min = 1, max = 10) #' #' # Sample offsets #' m <- 10*runif(n = n) #' #' # Blood pressure measurements #' x <- t #' for(i in 1:n) x[i, 1:n.i[i]] <- sin(phi[i] * 2*pi/max.n.i * t[i, 1:n.i[i]]) + m[i] #' #' # Matrix with covariates z #' q <- 2 # Number of covariates #' z <- matrix(rnorm(n = n*q), nrow = n, ncol = q) #' #' # Generate outcomes #' temp <- phi*min(m, 7) #' temp <- 40*temp #' prob <- 1/(1+exp( 2*( median(temp)-temp ) )) #' y <- rbinom(n = n, size = 1, prob = prob) #' #' xx <- list() #' for(i in 1:n) xx[[i]] <- approxfun(x = t[i,1:n.i[i]], y = x[i,1:n.i[i]], rule = 2) #' #' # Estimate f #' weights <- matrix(1/n.i, ncol = max.n.i, nrow = n)[!is.na(t)] #' f <- density( #' x = t(sapply(X = 1:n, FUN = function(i) c(xx[[i]](t[i,1:n.i[i]]), rep(NA, max.n.i-n.i[i])))), #' weights = weights/sum(weights), #' na.rm = T #' ) #' #' # Define CDF of f, F #' CDF <- c(0) #' for(i in 2:length(f$x)) CDF[i] <- CDF[i-1]+(f$x[i]-f$x[i-1])*(f$y[i]+f$y[i-1])/2 #' F <- approxfun(x = f$x, y = CDF/max(CDF), yleft = 0, yright = 1) #' #' psi <- list( #' function(x, t) abs(x(t)-x(t-1)) #' ) #' #' XWFresult <- xwfGridsearch(y = y, xx = xx, t = t, n.i = n.i, psi.list = psi, F = F, z = z) #' #' summary(XWFresult$GAMobject) #' XWFresult$b.left #' XWFresult$b.right #' #' #' @importFrom utils txtProgressBar setTxtProgressBar #' #' @export xwfGridsearch <- function(y, xx, t, n.i, psi.list = default_psi(), F = NULL, z = NULL, iter = 3, w = function(t, i, b, left) ifelse(left, min(1, (1-F(xx[[i]](t)))/(1-b)), min(1, F(xx[[i]](t))/b)), rel.shift = .001, progressbar = TRUE) { # Function that finds the optimal weighting functions via an adaptive grid search if(!is.function(psi.list[[1]])) stop("local feature 'psi.list' is not specified as a list of functions") if(!is.function(xx[[1]])) stop("trajectories 'xx' is not specified as a list of functions") n <- length(xx) if(length(n.i) == 1) n.i <- rep(n.i, n) # Find the begin and end time for each subject t.min <- apply(X = t, MARGIN = 1, FUN = min, na.rm = T) t.max <- apply(X = t, MARGIN = 1, FUN = max, na.rm = T) t.range <- t.max-t.min p <- length(psi.list) # Number of local features # Set up matrix to store XWFs XWFmatL <- matrix(data = NA_real_, nrow = p*2^(iter+1), ncol = n+2) XWFmatR <- matrix(data = NA_real_, nrow = p*2^(iter+1), ncol = n+2) countL <- 0 countR <- 0 # Functions that return the full set of, respectively, left and right XWFs, without recomputing that same XWF twice findXWFl <- function(p, b) { temp <- which(XWFmatL[ , 1] == p & XWFmatL[ , 2] == b) if(length(temp) == 1) return(XWFmatL[temp, -(1:2)]) countL <<- countL+1 XWFmatL[countL, 1:2] <<- c(p, b) XWFmatL[countL, -(1:2)] <<- xwf(xx = xx, t = t, n.i = n.i, psi = psi.list[[p]], w = function(t, i) w(t, i, b = b, left = TRUE), t.min = t.min, t.max = t.max, t.range = t.range) return(XWFmatL[countL, -(1:2)]) } findXWFr <- function(p, b) { temp <- which(XWFmatR[ , 1] == p & XWFmatR[ , 2] == b) if(length(temp) == 1) return(XWFmatR[temp, -(1:2)]) countR <<- countR+1 XWFmatR[countR, 1:2] <<- c(p, b) XWFmatR[countR, -(1:2)] <<- xwf(xx = xx, t = t, n.i = n.i, psi = psi.list[[p]], w = function(t, i) w(t, i, b = b, left = FALSE), t.min = t.min, t.max = t.max, t.range = t.range) return(XWFmatR[countR, -(1:2)]) } # Initialize wL and wR wL <- matrix(nrow = n, ncol = p) wR <- wL for(pp in 1:p) { wL[, pp] <- findXWFl(p = pp, b = .25) wR[, pp] <- findXWFr(p = pp, b = .75) } # Compute coresponding GAM UBRE score modelfit <- xwfGAM(wL = wL, wR = wR, y = y, z = z) score <- modelfit$gcv.ubre # Intialize weight function parameters (what we're trying to optimize) left <- rep(.25, p) right <- rep(.75, p) if(progressbar) pb <- txtProgressBar(max = iter, style = 3) for(s in 1:iter) { # Width of the grid at the current iteration grid.width <- .5/2^s # Optimize each XWF separately for(pp in 1:p) { # First, the left XWF wLl <- wL wLl[, pp] <- findXWFl(p = pp, b = left[pp] - grid.width) modelfit.l <- tryCatch( xwfGAM(wL = wLl, wR = wR, y = y, z = z), error = function(e) { cat("ERROR :",conditionMessage(e), "\n") return(modelfit) } ) score.l <- modelfit.l$gcv.ubre wLr <- wL wLr[, pp] <- findXWFl(p = pp, b = left[pp] + grid.width) modelfit.r <- tryCatch( xwfGAM(wL = wLr, wR = wR, y = y, z = z), error = function(e) { cat("ERROR :",conditionMessage(e), "\n") return(modelfit) } ) score.r <- modelfit.l$gcv.ubre temp <- which.min(c(score.l, score.r, score)) if(temp == 1) { left[pp] <- left[pp] - grid.width/2 wL <- wLl score <- score.l modelfit <- modelfit.l } else if(temp == 2) { left[pp] <- left[pp] + grid.width/2 wL <- wLr score <- score.r modelfit <- modelfit.r } # Second, the right XWF wRl <- wR wRl[, pp] <- findXWFr(p = pp, b = right[pp] - grid.width) modelfit.l <- tryCatch( xwfGAM(wL = wL, wR = wRl, y = y, z = z), error = function(e) { cat("ERROR :",conditionMessage(e), "\n") return(modelfit) } ) score.l <- modelfit.l$gcv.ubre wRr <- wR wRr[, pp] <- findXWFr(p = pp, b = right[pp] + grid.width) modelfit.r <- tryCatch( xwfGAM(wL = wL, wR = wRr, y = y, z = z), error = function(e) { cat("ERROR :",conditionMessage(e), "\n") return(modelfit) } ) score.r <- modelfit.r$gcv.ubre temp <- which.min(c(score.l, score.r, score)) if(temp == 1) { right[pp] <- right[pp] - grid.width/2 wR <- wRl score <- score.l modelfit <- modelfit.l } else if(temp == 2) { right[pp] <- right[pp] + grid.width/2 wR <- wRr score <- score.r modelfit <- modelfit.r } } if(progressbar) setTxtProgressBar(pb, s) } if(progressbar) close(pb) return(list(wL = wL, wR = wR, b.left = left, b.right = right, GAMobject = modelfit)) }
/scratch/gouwar.j/cran-all/cranData/xwf/R/xwfGridsearch.R
#' Cronbach's alpha #' @description \code{cronbach_alpha} computes Cronbach's alpha internal consistency reliability #' @param responses the oberved responses, 2d matrix #' @examples #' cronbach_alpha(model_3pl_gendata(1000, 20)$u) #' @importFrom stats var #' @export cronbach_alpha <- function(responses){ k <- ncol(responses) total_var <- var(rowSums(responses, na.rm=T)) item_var <- sum(apply(responses, 2, var, na.rm=T)) k / (k - 1) * (1 - item_var / total_var) } #' Spearman Brown Prophecy #' @description Use Spearman-brown formula to compute the predicted reliability #' when the test length is extened to n-fold or reversely the n-fold extension of #' test length in order to reach the targeted reliability #' @param n extend the test length to n-fold #' @param rho the reliability of current test #' @examples #' spearman_brown(2, .70) #' @export spearman_brown <- function(n, rho){ n * rho / (1 + (n - 1) * rho) } #' @rdname spearman_brown #' @param target the targeted reliability #' @examples #' spearman_brown_reverse(.70, .85) #' @export spearman_brown_reverse <- function(rho, target){ target * (1 - rho) / rho / (1 - target) }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module0_ctt_utils.R
#' #' Distribution of Expected Raw Scores #' @description Calculate the distribution of expected raw scores #' @param t the ability parameters, 1d vector #' @param a the item discrimination parameters, 1d vector #' @param b the item difficulty parameters, 1d vector #' @param c the item guessing parameters, 1d vector #' @export expected_raw_score_dist <- function(t, a, b, c){ if(length(b) != length(a) || length(b) != length(c)) stop('incompatible dimensions for item parameters:', length(a), length(b), length(c)) p <- model_3pl_prob(t, a, b, c) rs <- 1 for(i in 1:ncol(p)) rs <- cbind(rs * (1 - p[,i]), 0) + cbind(0, rs * p[, i]) rs }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module0_irt_utils.R
#' Root Mean Squared Error #' @description Root mean squared error (RMSE) of two numeric vectors/matrices #' @param x a numeric vector/matrix #' @param y a numeric vector/matrix #' @export rmse <- function(x, y){ x <- as.matrix(x) y <- as.matrix(y) if(any(dim(x) != dim(y))) stop("x and y have different dimensions") sqrt(colMeans((x - y)^2)) } #' Frequency Counts #' @description Frequency counts of a vector #' @param x a numeric or character vector #' @param values valid values, \code{NULL} to include all values #' @param rounding round percentage to n-th decimal places #' @export freq <- function(x, values=NULL, rounding=NULL){ if(is.null(values)) values <- sort(unique(x)) rs <- data.frame(table(factor(x, levels=values, labels=values)), stringsAsFactors=F) colnames(rs) <- c("value", "freq") rs$perc <- rs$freq / sum(rs$freq) rs$cum_freq <- cumsum(rs$freq) rs$cum_perc <- cumsum(rs$perc) if(!is.null(rounding)){ rs$perc <- round(rs$perc, rounding) rs$cum_perc <- round(rs$cum_perc, rounding) } rs } #' Hermite-Gauss Quadrature #' @description Pre-computed hermite gaussian quadratures points and weights #' @param degree the degree of hermite-gauss quadrature: '20', '11', '7' #' @keywords internal hermite_gauss <- function(degree=c('20', '11', '7')){ switch(match.arg(degree), '20'=list(t=c(-5.38748089001123,-4.60368244955074,-3.94476404011562,-3.34785456738321,-2.78880605842813,-2.25497400208927,-1.73853771211658,-1.23407621539532,-0.737473728545394,-0.245340708300901,0.245340708300901,0.737473728545394,1.23407621539532,1.73853771211658,2.25497400208927,2.78880605842813,3.34785456738321,3.94476404011562,4.60368244955074,5.38748089001123), w=c(2.22939364553415E-13,4.39934099227318E-10,1.08606937076928E-07,7.80255647853206E-06,0.000228338636016353,0.00324377334223786,0.0248105208874636,0.109017206020023,0.286675505362834,0.46224366960061,0.46224366960061,0.286675505362834,0.109017206020023,0.0248105208874636,0.00324377334223786,0.000228338636016353,7.80255647853206E-06,1.08606937076928E-07,4.39934099227318E-10,2.22939364553415E-13)), '11'=list(t=c(-3.66847084655958,-2.78329009978165,-2.02594801582575,-1.32655708449493,-0.656809566882099,0,0.656809566882099,1.32655708449493,2.02594801582575,2.78329009978165,3.66847084655958), w=c(1.43956039371425E-06,0.000346819466323345,0.0119113954449115,0.117227875167708,0.429359752356125,0.654759286914591,0.429359752356125,0.117227875167708,0.0119113954449115,0.000346819466323345,1.43956039371425E-06)), '7'=list(t=c(-2.651961356835233492447,-1.673551628767471445032,-0.8162878828589646630387,0,0.8162878828589646630387,1.673551628767471445032,2.651961356835233492447), w=c(9.71781245099519154149E-4,0.05451558281912703059218,0.4256072526101278005203,0.810264617556807326765,0.4256072526101278005203,0.0545155828191270305922,9.71781245099519154149E-4))) }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module0_stat_utils.R
#' Helper functions of Model Estimation #' @description miscellaneous helper functions for estimating IRT models #' @name estimate_helpers NULL #' @rdname estimate_helpers #' @description \code{estimate_nr_iteration} updates the parameters using the newton-raphson method #' @param param the parameter being estimated #' @param free TRUE to freely estimate specific parameters #' @param dv the first and second derivatives #' @param h_max the maximum value of h #' @param lr the learning rate #' @param bound the lower and upper bounds of the parameter #' @keywords internal estimate_nr_iteration <- function(param, free, dv, h_max, lr, bound){ h <- dv$dv1 / dv$dv2 h[is.na(h)] <- 0 h <- ifelse(abs(h) > h_max, sign(h) * h_max, h) * lr h[!free] <- 0 param <- param - h param[param < bound[1]] <- bound[1] param[param > bound[2]] <- bound[2] list(param=param, h=h) } #' @rdname estimate_helpers #' @param u the observed response, 2d matrix, values start from 0 #' @keywords internal model_polytomous_3dindex <- function(u){ n_p <- dim(u)[1] n_i <- dim(u)[2] n_c <- max(u) + 1 cbind(rep(1:n_p, n_i), rep(1:n_i, each=n_p), as.vector(u+1)) } #' @rdname estimate_helpers #' @keywords internal model_polytomous_3dresponse <- function(u){ n_c <- max(u) + 1 x <- array(0, dim=c(dim(u), n_c)) x[model_polytomous_3dindex(u)] <- 1 x }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module1_helpers.R
#' 3-parameter-logistic model #' @description Routine functions for the 3PL model #' @name model_3pl NULL #' @rdname model_3pl #' @param t ability parameters, 1d vector #' @param a discrimination parameters, 1d vector #' @param b difficulty parameters, 1d vector #' @param c guessing parameters, 1d vector #' @param D the scaling constant, 1.702 by default #' @examples #' with(model_3pl_gendata(10, 5), model_3pl_prob(t, a, b, c)) #' @export model_3pl_prob <- function(t, a, b, c, D=1.702){ p <- c + (1 - c) / (1 + exp(D * a * outer(b, t, '-'))) t(p) } #' @rdname model_3pl #' @examples #' with(model_3pl_gendata(10, 5), model_3pl_info(t, a, b, c)) #' @export model_3pl_info <- function(t, a, b, c, D=1.702){ p <- t(model_3pl_prob(t, a, b, c, D)) i <- (D * a * (p - c) / (1 - c))^2 * (1 - p) / p t(i) } #' @rdname model_3pl #' @param u observed responses, 2d matrix #' @param log True to return log-likelihood #' @examples #' with(model_3pl_gendata(10, 5), model_3pl_lh(u, t, a, b, c)) #' @export model_3pl_lh <- function(u, t, a, b, c, D=1.702, log=FALSE){ p <- model_3pl_prob(t, a, b, c, D) lh <- p^u * (1-p)^(1-u) if(log) lh <- log(lh) lh } #' @rdname model_3pl #' @param param the parameter of the new scale: 't' or 'b' #' @param mean the mean of the new scale #' @param sd the standard deviation of the new scale #' @importFrom stats sd #' @export model_3pl_rescale <- function(t, a, b, c, param=c("t", "b"), mean=0, sd=1){ scale <- switch(match.arg(param), "t"=t, "b"=b) slope <- sd / sd(scale) intercept <- mean - slope * mean(scale) t <- slope * t + intercept b <- slope * b + intercept a <- a / slope list(t=t, a=a, b=b, c=c) } #' @rdname model_3pl #' @param n_p the number of people to be generated #' @param n_i the number of items to be generated #' @param t_dist parameters of the normal distribution used to generate t-parameters #' @param a_dist parameters of the lognormal distribution used to generate a-parameters #' @param b_dist parameters of the normal distribution used to generate b-parameters #' @param c_dist parameters of the beta distribution used to generate c-parameters #' @param missing the proportion or number of missing responses #' @examples #' model_3pl_gendata(10, 5) #' model_3pl_gendata(10, 5, a=1, c=0, missing=.1) #' @importFrom stats rnorm rlnorm rbeta runif #' @export model_3pl_gendata <- function(n_p, n_i, t=NULL, a=NULL, b=NULL, c=NULL, D=1.702, t_dist=c(0, 1), a_dist=c(-.1, .2), b_dist=c(0, .7), c_dist=c(5, 46), missing=NULL){ if(is.null(t)) t <- rnorm(n_p, mean=t_dist[1], sd=t_dist[2]) if(is.null(a)) a <- rlnorm(n_i, meanlog=a_dist[1], sdlog=a_dist[2]) if(is.null(b)) b <- rnorm(n_i, mean=b_dist[1], sd=b_dist[2]) if(is.null(c)) c <- rbeta(n_i, shape1=c_dist[1], shape2=c_dist[2]) if(length(t) == 1) t <- rep(t, n_p) if(length(a) == 1) a <- rep(a, n_i) if(length(b) == 1) b <- rep(b, n_i) if(length(c) == 1) c <- rep(c, n_i) if(length(t) != n_p) stop('wrong dimensions of t parameters') if(length(a) != n_i) stop('wrong dimensions of a parameters') if(length(b) != n_i) stop('wrong dimensions of b parameters') if(length(c) != n_i) stop('wrong dimensions of c parameters') p <- model_3pl_prob(t, a, b, c, D) x <- array(runif(length(p)), dim(p)) u <- (p >= x) * 1L if(!is.null(missing)){ missing <- floor(ifelse(missing < 1, missing * n_p * n_i, missing)) idx <- sample(length(u), missing) u[cbind(ceiling(idx/n_i), (idx-1)%%n_i+1)] <- NA } list(u=u, t=t, a=a, b=b, c=c) } #' @rdname model_3pl #' @param type the type of plot: 'prob' for item characteristic curve (ICC) and #' 'info' for item information function curve (IIFC) #' @param total TRUE to sum values over items #' @param xaxis the values of x-axis #' @examples #' with(model_3pl_gendata(10, 5), model_3pl_plot(a, b, c, type="prob")) #' with(model_3pl_gendata(10, 5), model_3pl_plot(a, b, c, type="info", total=TRUE)) #' @import ggplot2 #' @importFrom reshape2 melt #' @export model_3pl_plot <- function(a, b, c, D=1.702, type=c('prob', 'info'), total=FALSE, xaxis=seq(-4, 4, .1)){ x <- switch(match.arg(type), "prob"=model_3pl_prob, "info"=model_3pl_info)(t=xaxis, a=a, b=b, c=c, D=D) if(total) x <- rowSums(x) x <- data.frame(theta=xaxis, x) x <- melt(x, id.vars="theta") ggplot(x, aes_string(x="theta", y="value", color="variable")) + geom_line() + xlab(expression(theta)) + ylab('') + guides(color=FALSE) + theme_bw() + theme(legend.key=element_blank()) } #' @rdname model_3pl #' @param show_mle TRUE to print maximum likelihood estimates #' @examples #' with(model_3pl_gendata(5, 50), model_3pl_plot_loglh(u, a, b, c, show_mle=TRUE)) #' @import ggplot2 #' @importFrom reshape2 melt #' @export model_3pl_plot_loglh <- function(u, a, b, c, D=1.702, xaxis=seq(-4, 4, .1), show_mle=FALSE){ p <- model_3pl_prob(xaxis, a, b, c, D) lh <- log(p) %*% t(u) + log(1 - p) %*% t(1 - u) if(show_mle) print(apply(lh, 2, function(x){xaxis[which.max(x)]})) x <- data.frame(theta=xaxis, lh) x <- melt(x, id.vars="theta") ggplot(x, aes_string(x="theta", y="value", color="variable")) + geom_line() + xlab(expression(theta)) + ylab("Log-likelihood") + guides(color=FALSE) + theme_bw() }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module1_model_3pl.R
#' Generalized Partial Credit Model #' @description Routine functions for the GPCM #' @name model_gpcm NULL #' @rdname model_gpcm #' @param t ability parameters, 1d vector #' @param a discrimination parameters, 1d vector #' @param b item location parameters, 1d vector #' @param d item category parameters, 2d vector #' @param D the scaling constant, 1.702 by default #' @param insert_d0 insert an initial category value #' @details #' Use \code{NA} to represent unused category. #' @examples #' with(model_gpcm_gendata(10, 5, 3), model_gpcm_prob(t, a, b, d)) #' @export model_gpcm_prob <- function(t, a, b, d, D=1.702, insert_d0=NULL){ if(!is.null(insert_d0)) d <- cbind(insert_d0, d) p <- -1 * outer(b - d, t, '-') * a * D p <- apply(p, c(1, 3), function(x) { x <- exp(cumsum(x)) x / sum(x, na.rm=TRUE) }) aperm(p, c(3, 2, 1)) } #' @rdname model_gpcm #' @examples #' with(model_gpcm_gendata(10, 5, 3), model_gpcm_info(t, a, b, d)) #' @export model_gpcm_info <- function(t, a, b, d, D=1.702, insert_d0=NULL){ p <- model_gpcm_prob(t, a, b, d, D, insert_d0) n_i <- dim(p)[2] n_c <- dim(p)[3] if(length(a) == 1) a <- rep(a, n_i) rs <- array(NA, dim=dim(p)) for(j in 1:n_i) rs[,j,] <- (D * a[j])^2 * p[,j,] * colSums(1:n_c * t(p[,j,]) * outer(1:n_c, colSums(t(p[,j,]) * 1:n_c), '-')) rs } #' @rdname model_gpcm #' @param u the observed scores (starting from 0), 2d matrix #' @param log TRUE to return log-likelihood #' @examples #' with(model_gpcm_gendata(10, 5, 3), model_gpcm_lh(u, t, a, b, d)) #' @export model_gpcm_lh <- function(u, t, a, b, d, D=1.702, insert_d0=NULL, log=FALSE){ p <- model_gpcm_prob(t, a, b, d, D, insert_d0) ix <- model_polytomous_3dindex(u) lh <- array(p[ix], dim=dim(u)) if(log) lh <- log(lh) lh } #' @rdname model_gpcm #' @param n_p the number of people to be generated #' @param n_i the number of items to be generated #' @param n_c the number of score categories #' @param sort_d \code{TRUE} to sort d parameters for each item #' @param t_dist parameters of the normal distribution used to generate t-parameters #' @param a_dist parameters of the lognormal distribution parameters of a-parameters #' @param b_dist parameters of the normal distribution used to generate b-parameters #' @param missing the proportion or number of missing responses #' @examples #' model_gpcm_gendata(10, 5, 3) #' model_gpcm_gendata(10, 5, 3, missing=.1) #' @importFrom stats rnorm rlnorm runif #' @export model_gpcm_gendata <- function(n_p, n_i, n_c, t=NULL, a=NULL, b=NULL, d=NULL, D=1.702, sort_d=FALSE, t_dist=c(0, 1), a_dist=c(-.1, .2), b_dist=c(0, .8), missing=NULL){ if(is.null(t)) t <- rnorm(n_p, mean=t_dist[1], sd=t_dist[2]) if(is.null(a)) a <- rlnorm(n_i, meanlog=a_dist[1], sdlog=a_dist[2]) if(is.null(b)) b <- rnorm(n_i, mean=b_dist[1], sd=b_dist[2]) if(is.null(d)) { d <- matrix(rnorm(n_i * n_c, mean=0, sd=1), nrow=n_i, ncol=n_c) d[, 1] <- 0 d[, -1] <- d[, -1] - rowMeans(d[, -1]) if(sort_d) d[, -1] <- t(apply(d[, -1], 1, sort)) } if(length(t) == 1) t <- rep(t, n_p) if(length(a) == 1) a <- rep(a, n_i) if(length(t) != n_p) stop('wrong dimensions for t') if(length(a) != n_i) stop('wrong dimensions for a') if(length(b) != n_i) stop('wrong dimensions for b') if(nrow(d) != n_i || ncol(d) != n_c) stop('wrong dimensions for d') p <- model_gpcm_prob(t, a, b, d, D, NULL) u <-apply(p, 2, function(x) rowSums(runif(n_p) >= t(apply(x, 1, cumsum)))) if(!is.null(missing)){ missing <- floor(ifelse(missing < 1, missing * n_p * n_i, missing)) idx <- sample(length(u), missing) u[cbind(ceiling(idx/n_i), (idx-1)%%n_i+1)] <- NA } list(u=u, t=t, a=a, b=b, d=d) } #' @rdname model_gpcm #' @param param the parameter of the new scale: 't' or 'b' #' @param mean the mean of the new scale #' @param sd the standard deviation of the new scale #' @importFrom stats sd #' @export model_gpcm_rescale <- function(t, a, b, d, param=c("t", "b"), mean=0, sd=1){ scale <- switch(match.arg(param), "t"=t, "b"=b) slope <- sd / sd(scale) intercept <- mean - slope * mean(scale) t <- slope * t + intercept b <- slope * b + intercept a <- a / slope d <- d * slope list(t=t, a=a, b=b, d=d) } #' @rdname model_gpcm #' @param type the type of plot, prob for ICC and info for IIFC #' @param total TRUE to sum values over items #' @param by_item TRUE to combine categories #' @param xaxis the values of x-axis #' @examples #' # Figure 1 in Muraki, 1992 (APM) #' b <- matrix(c(-2,0,2,-.5,0,2,-.5,0,2), nrow=3, byrow=TRUE) #' model_gpcm_plot(a=c(1,1,.7), b=rowMeans(b), d=rowMeans(b)-b, D=1.0, insert_d0=0) #' # Figure 2 in Muraki, 1992 (APM) #' b <- matrix(c(.5,0,NA,0,0,0), nrow=2, byrow=TRUE) #' model_gpcm_plot(a=.7, b=rowMeans(b, na.rm=TRUE), d=rowMeans(b, na.rm=TRUE)-b, D=1.0, insert_d0=0) #' # Figure 3 in Muraki, 1992 (APM) #' b <- matrix(c(1.759,-1.643,3.970,-2.764), nrow=2, byrow=TRUE) #' model_gpcm_plot(a=c(.778,.946), b=rowMeans(b), d=rowMeans(b)-b, D=1.0, insert_d0=0) #' # Figure 1 in Muraki, 1993 (APM) #' b <- matrix(c(0,-2,4,0,-2,2,0,-2,0,0,-2,-2,0,-2,-4), nrow=5, byrow=TRUE) #' model_gpcm_plot(a=1, b=rowMeans(b), d=rowMeans(b)-b, D=1.0) #' # Figure 2 in Muraki, 1993 (APM) #' b <- matrix(c(0,-2,4,0,-2,2,0,-2,0,0,-2,-2,0,-2,-4), nrow=5, byrow=TRUE) #' model_gpcm_plot(a=1, b=rowMeans(b), d=rowMeans(b)-b, D=1.0, type='info', by_item=TRUE) #' @import ggplot2 #' @importFrom stats aggregate #' @export model_gpcm_plot <- function(a, b, d, D=1.702, insert_d0=NULL, type=c('prob', 'info'), by_item=FALSE, total=FALSE, xaxis=seq(-6, 6, .1)){ rs <- switch(match.arg(type), "prob"=model_gpcm_prob, "info"=model_gpcm_info)(xaxis, a, b, d, D, insert_d0) n_p <- dim(rs)[1] n_i <- dim(rs)[2] n_c <- dim(rs)[3] y <- NULL for(i in 1:n_i) y <- rbind(y, data.frame(theta=rep(xaxis, n_c), item=paste('Item', i), category=paste('Category', rep(1:n_c, each=n_p)), x=as.vector(rs[, i, ]))) if(by_item) y <- rbind(y, cbind(aggregate(y$x, by=list(theta=y$theta, item=y$item), sum), category='Total')) if(total) y <- cbind(aggregate(y$x, by=list(theta=y$theta, category=y$category), sum), item='Total') y <- y[!is.na(y$x),] ggplot(y, aes_string(x="theta", y="x", color="category")) + geom_line() + facet_wrap(~item, scales='free') + xlab(expression(theta)) + ylab(type) + guides(color=FALSE) + theme_bw() + theme(legend.key=element_blank()) } #' @rdname model_gpcm #' @param show_mle TRUE to print maximum likelihood values #' @examples #' with(model_gpcm_gendata(5, 50, 3), model_gpcm_plot_loglh(u, a, b, d)) #' @import ggplot2 #' @export model_gpcm_plot_loglh <- function(u, a, b, d, D=1.702, insert_d0=NULL, xaxis=seq(-6, 6, .1), show_mle=FALSE){ n_p <- dim(u)[1] n_i <- dim(u)[2] n_t <- length(xaxis) rs <- array(NA, dim=c(n_p, n_t)) for(i in 1:n_t) rs[, i] <- rowSums(model_gpcm_lh(u, rep(xaxis[i], n_p), a, b, d, D, insert_d0, log=TRUE)) if(show_mle) print(apply(rs, 1, function(x){xaxis[which.max(x)]})) rs <- data.frame(theta=rep(xaxis, each=n_p), people=rep(1:n_p, n_t), value=as.vector(rs)) rs$people <- factor(rs$people) ggplot(rs, aes_string(x="theta", y="value", color="people")) + geom_line() + xlab(expression(theta)) + ylab("Log-likelihood") + guides(color=FALSE) + theme_bw() }
/scratch/gouwar.j/cran-all/cranData/xxIRT/R/module1_model_gpcm.R