Sunday 26 November 2017

Cómo De Salir Datos De Los Datos


Base R tiene una gran cantidad de funcionalidad útil para series de tiempo, en particular en el paquete de estadísticas. Esto se complementa con muchos paquetes en CRAN, que se resumen brevemente a continuación. También hay una considerable superposición entre las herramientas para las series de tiempo y las de las vistas de las tareas de Econometría y Finanzas. Los paquetes de esta vista se pueden estructurar en los siguientes temas. Si piensa que falta algún paquete en la lista, háganoslo saber. Infraestructura. Base R contiene una infraestructura sustancial para representar y analizar datos de series de tiempo. La clase fundamental es quottsquot que puede representar series temporales regularmente espaciadas (usando sellos de tiempo numéricos). Por lo tanto, es particularmente adecuado para datos anuales, mensuales, trimestrales, etc. Los promedios móviles se calculan por ma desde el pronóstico. Y rollmean del zoológico. Este último también proporciona una aplicación de rol de función general. Junto con otras funciones de estadísticas de balanceo específicas. Roll proporciona funciones paralelas para calcular estadísticas de balanceo. Gráficos. Las gráficas de series temporales se obtienen con el gráfico () aplicado a los objetos ts. (Parciales) las funciones de autocorrelación se implementan en acf () y pacf (). Versiones alternativas son proporcionadas por Acf () y Pacf () en el pronóstico. Junto con una pantalla de combinación usando tsdisplay (). SDD proporciona diagramas de dependencia en serie más generales, mientras que dCovTS calcula y traza las funciones de covarianza y correlación de distancia de series de tiempo. Las visualizaciones estacionales se obtienen mediante el uso de monthplot () en stats y seasonplot en el pronóstico. Wats implementa gráficos de series de tiempo envolventes. Ggseas proporciona gráficos ggplot2 para series ajustadas estacionalmente y estadísticas de balanceo. Dygraphs proporciona una interfaz a la serie de gráficos interactivos de Dygraphs. ZRA traza objetos de pronóstico del paquete de pronóstico usando dígrafos. Los pronósticos y los vars son los diagramas básicos de las distribuciones de pronósticos. Los diagramas de ventiladores más flexibles de cualquier distribución secuencial se implementan en fanplot. Los quottsquot de clase sólo pueden ocuparse de sellos de tiempo numéricos, pero muchas más clases están disponibles para almacenar información de tiempo / fecha e informática con ella. Para una visión general vea R Help Desk: Clases de fecha y hora en R de Gabor Grothendieck y Thomas Petzoldt en R News 4 (1). 29-32. Las clases quotyearmonquot y quotyearqtrquot del zoológico permiten un cómputo más conveniente con observaciones mensuales y trimestrales, respectivamente. Clase quotDatequot del paquete base es la clase básica para tratar las fechas en los datos diarios. Las fechas se almacenan internamente como el número de días desde 1970-01-01. El paquete cron proporciona clases para las fechas (). Horas () y fecha / hora (intra-día) en cron (). No hay soporte para zonas horarias y el horario de verano. Internamente, los objetos quotchronquot son días (fraccionados) desde 1970-01-01. Las clases quotPOSIXctquot y quotPOSIXlt implementan el estándar POSIX para información de fecha / hora (intra-día) y también admiten zonas horarias y horario de verano. Sin embargo, los cálculos de la zona horaria requieren cierta atención y pueden depender del sistema. Internamente, los objetos quotPOSIXctquot son el número de segundos desde 1970-01-01 00:00:00 GMT. El paquete lubridate proporciona funciones que facilitan ciertos cálculos basados ​​en POSIX. La clase quottimeDatequot se proporciona en el paquete timeDate (anteriormente: fCalendar). Está dirigido a la información financiera de tiempo / fecha y se ocupa de los husos horarios y los horarios de ahorro de luz a través de un nuevo concepto de centros cuantitativos. Internamente, almacena toda la información en quotPOSIXctquot y hace todos los cálculos en GMT solamente. Funcionalidad de calendario, p. Incluyendo información sobre fines de semana y feriados para diversas bolsas de valores, también está incluido. El paquete tis proporciona la clase quottiquot para la información de hora / fecha. La clase quotmondatequot del paquete mondate facilita la computación con fechas en términos de meses. El paquete tempdisagg incluye métodos para la desagregación temporal y la interpolación de una serie temporal de baja frecuencia a una serie de frecuencias más altas. TimeProjection extrae los componentes de tiempo útil de un objeto de fecha, como día de la semana, fin de semana, día festivo, día del mes, etc., y lo coloca en un marco de datos. Como se mencionó anteriormente, quottsquot es la clase básica para series de tiempo regularmente espaciadas usando sellos de tiempo numéricos. El paquete del zoológico proporciona infraestructura para series temporales regulares e irregularmente espaciadas usando clases arbitrarias para los sellos de tiempo (es decir, permitiendo todas las clases de la sección anterior). Está diseñado para ser lo más consistente posible con quottsquot. La coacción desde y hacia quotzooquot está disponible para todas las otras clases mencionadas en esta sección. El paquete xts se basa en zoológico y proporciona un manejo uniforme de Rs diferentes clases de datos basadas en tiempo. Varios paquetes implementan series temporales irregulares basadas en sellos de tiempo quotPOSIX, especialmente destinados a aplicaciones financieras. Estos incluyen quotitsquot de su. Cita de tseries. Y quotftsquot de fts. La clase quottimeSeriesquot en timeSeries (anteriormente: fSeries) implementa series de tiempo con quottimeDatequot sellos de tiempo. La clase quottisquot in tis implementa series de tiempo con sellos de tiempo quottiquot. El paquete tframe contiene infraestructura para establecer intervalos de tiempo en diferentes formatos. Pronóstico y modelado univariado El paquete de pronóstico proporciona una clase y métodos para predicciones de series de tiempo univariadas, y proporciona muchas funciones implementando diferentes modelos de pronóstico incluyendo todos aquellos en el paquete de estadísticas. Desvanecimiento exponencial . HoltWinters () en stats proporciona algunos modelos básicos con optimización parcial, ets () del paquete de pronóstico proporciona un conjunto más grande de modelos e instalaciones con optimización completa. El paquete MAPA combina modelos de suavizado exponencial a diferentes niveles de agregación temporal para mejorar la precisión de pronóstico. Smooth implementa algunas generalizaciones de suavizado exponencial. El método theta se implementa en la función thetaf del paquete de pronóstico. Una implementación alternativa y extendida se proporciona en forectheta. Modelos autorregresivos. Ar () en las estadísticas (con la selección del modelo) y FitAR para los modelos del subconjunto AR. Modelos ARIMA. Arima () en stats es la función básica de los modelos ARIMA, SARIMA, ARIMAX y subconjunto ARIMA. Se mejora en el paquete de pronóstico a través de la función Arima () junto con auto. arima () para la selección automática de órdenes. Arma () en el paquete tseries proporciona diferentes algoritmos para los modelos ARMA y subconjunto ARMA. FitARMA implementa un algoritmo rápido MLE para los modelos ARMA. El paquete gsarima contiene funcionalidad para la simulación generalizada de series temporales SARIMA. El paquete mar1s maneja RA multiplicativo (1) con procesos estacionales. TSTutorial proporciona un tutorial interactivo para el modelado de Box-Jenkins. Los intervalos de predicción mejorados para ARIMA y los modelos de series temporales estructurales son proporcionados por tsPI. Modelos periódicos ARMA. Pera y partsm para modelos periódicos de series temporales autorregresivas y perARMA para el modelado periódico ARMA y otros procedimientos para el análisis periódico de series temporales. Modelos ARFIMA. Algunas instalaciones para los modelos ARFIMA fraccionados diferenciados se proporcionan en el paquete fracdiff. El paquete arfima tiene instalaciones más avanzadas y generales para los modelos ARFIMA y ARIMA, incluyendo modelos de regresión dinámica (función de transferencia). ArmaFit () del paquete fArma es una interfaz para los modelos ARIMA y ARFIMA. El ruido gaussiano fraccional y los modelos simples para las series de tiempo de decaimiento hiperbólico se manejan en el paquete FGN. Los modelos de función de transferencia son proporcionados por la función arimax en el paquete TSA y la función arfima en el paquete arfima. La detección de valores atípicos siguiendo el enfoque de Chen-Liu es proporcionada por tsoutliers. Los modelos estructurales se implementan en StructTS () en stats, y en stsm y stsm. class. KFKSDS proporciona una implementación ingenua del filtro de Kalman y suavizadores para modelos de espacio de estados univariados. Los modelos de series de tiempo estructurales bayesianos se implementan en bsts. Las series de tiempo no gaussianas se pueden manejar con modelos de espacio de estado GLARMA vía glarma. Y utilizando Modelos de Puntuación Autoregressive Generalizada en el paquete GAS. Los modelos de Auto-Regresión condicional que utilizan métodos Monte Carlo Likelihood se implementan en mclcar. Modelos GARCH. Garch () de tseries se ajusta a los modelos básicos de GARCH. Muchas variaciones en los modelos de GARCH son proporcionadas por rugarch. Otros paquetes GARCH univariados incluyen fGarch que implementa modelos ARIMA con una amplia clase de innovaciones GARCH. Hay muchos más paquetes de GARCH descritos en la vista de tareas de Finanzas. Los modelos de volatilidad estocástica son manejados por stochvol en un marco bayesiano. Los modelos de series temporales de conteo se manejan en los paquetes tscount y acp. ZIM proporciona Modelos Inflados Cero para series de tiempo de conteo. Tsintermittent implementa varios modelos para analizar y pronosticar series de tiempo de demanda intermitente. Las series temporales censuradas pueden ser modeladas usando centavos y carx. Las pruebas de Portmanteau se proporcionan a través de Box. test () en el paquete de estadísticas. Pruebas adicionales son realizadas por portes y WeightedPortTest. La detección de puntos de cambio se proporciona en strucchange (usando modelos de regresión lineal), en tendencia (usando pruebas no paramétricas) y en wbsts (usando segmentación binaria salvaje). El paquete de punto de cambio proporciona muchos métodos de punto de cambio populares, y ecp hace detección de punto de cambio no paramétrico para series univariadas y multivariantes. La detección en línea de puntos de cambio para series cronológicas univariadas y multivariadas es proporcionada por CPD online. InspectChangepoint utiliza una proyección dispersa para estimar los puntos de cambio en series temporales de alta dimensión. La imputación de series temporales es proporcionada por el paquete imputeTS. Algunas instalaciones más limitadas están disponibles utilizando na. interp () del paquete de pronóstico. Los pronósticos se pueden combinar usando ForecastCombinations, que soporta los métodos más utilizados para combinar pronósticos. ForecastHybrid proporciona funciones para previsiones de conjuntos, combinando enfoques del paquete de pronóstico. Opera tiene facilidades para predicciones en línea basadas en combinaciones de pronósticos proporcionados por el usuario. La evaluación de pronósticos se proporciona en la función accuracy () de la previsión. La evaluación de la predicción distributiva usando reglas de puntuación está disponible en scoringRules Miscellaneous. Ltsa contiene métodos para el análisis lineal de series temporales, timsac para el análisis y control de series temporales y tsbugs para modelos BUGS de series temporales. La estimación de la densidad espectral es proporcionada por el espectro () en el paquete de estadísticas, incluyendo el periodograma, el periodograma suavizado y las estimaciones de AR. La inferencia espectral bayesiana viene dada por bspec. Quantspec incluye métodos para calcular y representar los periodogramas de Laplace para series temporales univariadas. El periodograma de Lomb-Scargle para series temporales muestradas de manera irregular se calcula mediante lomb. El espectro utiliza transformadas de Fourier y Hilbert para el filtrado espectral. Psd produce estimados de densidad espectral adaptativos, seno-multitaper. Kza proporciona filtros adaptativos Kolmogorov-Zurbenko incluyendo detección de rotura, análisis espectral, wavelets y transformadas de Fourier KZ. Multitaper también proporciona algunas herramientas de análisis espectral multitaper. Métodos Wavelet. El paquete de wavelets incluye computar filtros wavelet, transformadas wavelet y análisis multiresolución. Los métodos wavelet para el análisis de series temporales basados ​​en Percival y Walden (2000) se dan en wmtsa. WaveletComp proporciona algunas herramientas para el análisis basado en wavelets de series temporales univariadas y bivariadas incluyendo ondas cruzadas, pruebas de diferencia de fase y significantes. Biwavelet puede usarse para trazar y calcular los espectros de wavelets, espectros de onda cruzada y coherencia de wavelet de series temporales no estacionarias. También incluye funciones para agrupar series temporales basadas en las (des) similitudes en su espectro. Pruebas de ruido blanco utilizando wavelets son proporcionados por hwwntest. Se pueden encontrar métodos wavelet adicionales en los paquetes de brainwaver. Rwt. Waveslim Wavethresh y mvcwt. La regresión armónica utilizando términos de Fourier se implementa en la Reacción Armónica. El paquete de previsión también proporciona algunas facilidades de regresión de armónicos simples a través de la función fourier. Descomposición y filtración Filtros y suavizado. Filter () en stats proporciona un filtrado lineal promedio autorregresivo y móvil de series temporales univariadas múltiples. El paquete Robfilter proporciona varios filtros robustos de series temporales, mientras que mFilter incluye diversos filtros de series temporales útiles para suavizar y extraer componentes de tendencia y cíclicos. Smooth () del paquete de estadísticas calcula Tukeys que ejecutan los suavizadores medianos, 3RS3R, 3RSS, 3R, etc. sleekts calcula el 4253H dos veces el método de suavizado. Descomposición. La descomposición estacional se discute a continuación. La descomposición basada en la auto-regresión es proporcionada por ArDec. Rmaf utiliza un refinado filtro de media móvil para la descomposición. El Análisis de Espectro Singular se implementa en Rssa y métodos espectrales. La descomposición en modo empírico (EMD) y el análisis espectral de Hilbert son proporcionados por EMD. Las herramientas adicionales, incluyendo EMD del conjunto, están disponibles en hht. Una implementación alternativa del conjunto EMD y su variante completa están disponibles en Rlibeemd. Descomposición estacional. El paquete stats proporciona descomposición clásica en descomposición (). Y la descomposición STL en stl (). La descomposición STL mejorada está disponible en stlplus. StR proporciona la descomposición Seasonal-Trend basada en la regresión. X12 proporciona una envoltura para los binarios X12 que deben instalarse primero. X12GUI proporciona una interfaz gráfica de usuario para x12. Los binarios X-13-ARIMA-SEATS se proporcionan en el paquete x13binary, con una interfaz estacional proporcionando R. Análisis de la estacionalidad. El paquete de bfast proporciona métodos para detectar y caracterizar cambios abruptos dentro de la tendencia y componentes estacionales obtenidos de una descomposición. Npst proporciona una generalización de la prueba de estacionalidad de Hewitts. temporada. Análisis estacional de datos de salud incluyendo modelos de regresión, crossover de casos estratificados en el tiempo, funciones de trazado y chequeos residuales. Mares Análisis estacional y gráficos, especialmente para climatología. Deseasonalize Desestacionalización óptima para las series de tiempo geofísico utilizando ajuste AR. Stationarity, Unit Roots, y Cointegration Stationarity y raíces unitarias. Tseries proporciona varias pruebas de estacionariedad y raíz unitaria, incluyendo Dickey-Fuller aumentado, Phillips-Perron y KPSS. Las implementaciones alternativas de las pruebas ADF y KPSS se encuentran en el paquete urca, que también incluye otros métodos como las pruebas Elliott-Rothenberg-Stock, Schmidt-Phillips y Zivot-Andrews. El paquete fUnitRoots también proporciona la prueba MacKinnon, mientras que uroot proporciona pruebas estacionales de raíz unitaria. CADFtest proporciona implementaciones tanto de la ADF estándar como de una prueba ADF (CADF) aumentada en covariable. Estacionaria local. Locs proporciona una prueba de estacionaridad local y calcula la autocovariancia localizada. La determinación de la determinación de la costera de series temporales viene dada por costat. LSTS tiene funciones para el análisis de series de tiempo estacionario localmente. Los modelos de onda fija localmente estacionarios para series de tiempo no estacionarias se implementan en wavethresh (incluyendo la estimación, el trazado y la funcionalidad de simulación para espectros que varían en el tiempo). Cointegración. El método Engle-Granger de dos pasos con la prueba de cointegración Phillips-Ouliaris se implementa en tseries y urca. Este último contiene adicionalmente funcionalidad para las pruebas Johansen trace y lambda-max. TsDyn proporciona la prueba de Johansens y AIC / BIC selección simultánea de rango-lag. CommonTrend proporciona herramientas para extraer y trazar tendencias comunes de un sistema de cointegración. La estimación de parámetros y la inferencia en una regresión de cointegración se implementan en cointReg. Análisis no lineal de series temporales Autorregulación no lineal. Varias formas de autorregresión no lineal están disponibles en tsDyn incluyendo AR aditivo, redes neurales, modelos SETAR y LSTAR, umbral VAR y VECM. También se proporciona autoregresión de red neuronal en GMDH. BentcableAR implementa la autorregresión Bent-Cable. BAYSTAR proporciona un análisis bayesiano de modelos umbral autorregresivos. TseriesChaos proporciona una implementación R de los algoritmos del proyecto TISEAN. Autoregresión Los modelos de conmutación de Markov se proporcionan en MSwM. Mientras que las mezclas dependientes de los modelos de Markov latentes se dan en depmix y depmixS4 para series temporales categóricas y continuas. Pruebas. Diversas pruebas para la no linealidad se proporcionan en fNonlinear. TseriesEntropy pruebas de dependencia en serie no lineal basado en métricas de entropía. Las funciones adicionales para series temporales no lineales están disponibles en nlts y nonlinearTseries. El modelado y el análisis de la serie del tiempo de Fractal es proporcionado por el fractal. Fractalrock genera series de tiempo fractal con distribuciones de retornos no normales. Modelos dinámicos de regresión Modelos lineales dinámicos. Una interfaz conveniente para la adaptación de modelos de regresión dinámica a través de OLS está disponible en dynlm un enfoque mejorado que también funciona con otras funciones de regresión y más clases de series de tiempo se implementa en dyn. Se pueden montar ecuaciones de sistemas dinámicos más avanzadas usando dse. Los modelos de espacio de estados lineales gaussianos se pueden ajustar usando dlm (vía máxima verosimilitud, filtración / suavizado de Kalman y métodos Bayesianos), o usando bsts que usa MCMC. Las funciones para el modelado no lineal de retraso distribuido se proporcionan en dlnm. Los modelos de parámetros que varían en función del tiempo se pueden montar utilizando el paquete tpr. OrderedLasso se ajusta a un modelo lineal escaso con una restricción de orden en los coeficientes para manejar regresores rezagados donde los coeficientes disminuyen a medida que aumenta el desfase. El modelado dinámico de varios tipos está disponible en dynr, incluyendo modelos discretos y continuos, lineales y no lineales, y diferentes tipos de variables latentes. Modelos de series temporales multivariantes Los modelos vectoriales autorregresivos (VAR) se proporcionan a través de ar () en el paquete de estadísticas básicas, incluyendo la selección de pedidos a través de AIC. Estos modelos se limitan a ser estacionarios. MTS es un conjunto de herramientas para el análisis de series temporales multivariadas que incluyen VAR, VARMA, VARMA estacional, modelos VAR con variables exógenas, regresión multivariable con errores de series temporales y mucho más. Es posible que los modelos VAR no estacionarios estén instalados en el paquete mAr, lo que también permite modelos VAR en el espacio de los componentes principales. Sparsevar permite la estimación de modelos VAR y VECM dispersos, ecm proporciona funciones para la construcción de modelos VECM, mientras que BigVAR estima modelos VAR y VARX con sanciones estructuradas por lazo. Los modelos y redes VAR automatizados están disponibles en autovarCore. Modelos más elaborados se proporcionan en el paquete vars. TsDyn. EstVARXls () en dse. Y un enfoque Bayesiano está disponible en MSBVAR. Otra implementación con intervalos de predicción bootstrap se da en VAR. etp. MlVAR proporciona autorregresión vectorial multi-nivel. VARsignR proporciona rutinas para identificar choques estructurales en modelos VAR usando restricciones de signo. Los modelos VARIMA y los modelos de espacio de estado se proporcionan en el paquete dse. EvalEst facilita los experimentos de Monte Carlo para evaluar los métodos de estimación asociados. Los modelos de corrección de errores vectoriales están disponibles a través de la urca. Vars y tsDyn, incluyendo versiones con restricciones estructurales y umbrales. Análisis de componentes de series temporales. El análisis de factores de series temporales se proporciona en tsfa. ForeCA implementa el análisis de componentes forecables mediante la búsqueda de las mejores transformaciones lineales que hacen que una serie temporal multivariada sea lo más previsible posible. PCA4TS encuentra una transformación lineal de una serie de tiempo multivariable dando secundario-dimensional subseries que están uncorrelated con uno a. Los modelos de espacio de estado multivariable se implementan en el paquete FKF (Fast Kalman Filter). Esto proporciona modelos de espacio de estados relativamente flexibles a través de la función fkf (): los parámetros de espacio de estado se permiten variar en el tiempo y las intercepciones se incluyen en ambas ecuaciones. Una implementación alternativa es proporcionada por el paquete de KFAS que proporciona un filtro de Kalman multivariable rápido, más suave, simulación más suave y previsión. Otra implementación se da en el paquete dlm que también contiene herramientas para convertir otros modelos multivariados en forma de espacio de estado. Dlmodeler proporciona una interfaz unificada para dlm. KFAS y FKF. MARSS se ajusta a los modelos de estado-espacio autorregresivos multivariados y constreñidos sin restricciones usando un algoritmo EM. Todos estos paquetes suponen que los términos de error de observación y de estado no están correlacionados. Los procesos de Markov parcialmente observados son una generalización de los modelos de espacio de estado multivariados lineales usuales, permitiendo modelos no-Gaussianos y no lineales. Estos se implementan en el paquete de pompa. Modelos de volatilidad estocástica multivariable (utilizando factores latentes) son proporcionados por factores tochvol. Análisis de grandes grupos de series temporales La agrupación de series temporales se implementa en TSclust. Dtwclust. BNPTSclust y pdc. TSdist proporciona medidas de distancia para datos de series de tiempo. Jmotif implementa herramientas basadas en la discretización simbólica de series temporales para encontrar motivos en series de tiempo y facilita la clasificación de series temporales interpretables. Los métodos para trazar y pronosticar colecciones de series temporales jerárquicas y agrupadas son proporcionados por hts. Ladrón usa métodos jerárquicos para conciliar pronósticos de series de tiempo temporalmente agregadas. Un método alternativo para conciliar las previsiones de series de tiempo jerárquicas es proporcionado por gtop. Ladrón Modelos de tiempo continuo Modelado autorregresivo de tiempo continuo en cts. Sim. DiffProc simula y modela ecuaciones diferenciales estocásticas. La simulación y la inferencia para ecuaciones diferenciales estocásticas son proporcionadas por sde y yuima. Bootstrapping. El paquete de arranque proporciona la función tsboot () para el arranque en serie temporal, incluido el bloqueo de arranque con varias variantes. Tsbootstrap () de tseries proporciona estacionamiento rápido y bloques de arranque. El bootstrap máximo de entropía para series de tiempo está disponible en meboot. Timesboot calcula el CI de arranque para la muestra ACF y el periodograma. BootPR calcula la predicción corregida por sesgo y los intervalos de predicción de boostrap para series temporales autorregresivas. Datos de Makridakis, Wheelwright y Hyndman (1998) Pronóstico: los métodos y aplicaciones se proporcionan en el paquete fma. Datos de Hyndman, Koehler, Ord y Snyder (2008) Las predicciones con suavizado exponencial se encuentran en el paquete expsmooth. Datos de Hyndman y Athanasopoulos (2013) Pronóstico: los principios y la práctica están en el paquete fpp. Los datos de la competición M y de la competencia M3 se proporcionan en el paquete Mcomp. Los datos de la competencia M4 se dan en M4comp. Mientras que Tcomp proporciona datos del Concurso de Pronósticos de Turismo de la IJF 2010. Pdfetch proporciona instalaciones para descargar series económicas y financieras de fuentes públicas. Los datos del portal en línea de Quandl a los conjuntos de datos financieros, económicos y sociales pueden ser consultados interactivamente usando el paquete de Quandl. Los datos del portal en línea de Datamarket se pueden obtener usando el paquete rdatamarket. Los datos de Cryer y Chan (2010) están en el paquete TSA. Los datos de Shumway y Stoffer (2011) están en el paquete astsa. Datos de Tsay (2005) El análisis de las series de tiempo financiero está en el paquete FinTS, junto con algunas funciones y archivos de script necesarios para trabajar algunos de los ejemplos. TSdbi proporciona una interfaz común a las bases de datos de series de tiempo. Fama proporciona una interfaz para las bases de datos de la serie de tiempo FAME AER y Ecdat contienen muchos conjuntos de datos (incluyendo datos de series de tiempo) de muchos libros de texto de econometría dtw. Algoritmos de deformación de tiempo dinámicos para calcular y trazar alineaciones por pares entre series de tiempo. EnsembleBMA. Modelo Bayesiano Promedio para crear pronósticos probabilísticos a partir de pronósticos de conjuntos y observaciones meteorológicas. Primeros avisos La alerta temprana señala una caja de herramientas para detectar transiciones críticas en eventos de series temporales. Convierte datos de eventos extraídos por máquina en series temporales multivariadas agregadas regulares. Comentarios. Análisis de la temporalidad fragmentada para investigar la retroalimentación en series de tiempo. LPStimeSeries tiene como objetivo encontrar la similitud de patrón de quotlearned para series de tiempo. MAR1 proporciona herramientas para preparar datos de series temporales de comunidades ecológicas para el modelado de AR multivariable. Redes Rutinas para la estimación de las redes parciales de correlación parcial de largo plazo para datos de series de tiempo. Paleots Modelización de la evolución en series temporales paleontológicas. Pastecs Regulación, descomposición y análisis de series espacio-temporales. Ptw. Deformación paramétrica del tiempo. RGENERATE proporciona herramientas para generar series de tiempo vectoriales. RMAWGEN es un conjunto de funciones S3 y S4 para la generación estocástica espacial multi-sitio de series cronológicas diarias de temperatura y precipitación utilizando modelos VAR. El paquete puede utilizarse en climatología e hidrología estadística. RSEIS. Herramientas sísmicas de análisis de series temporales. Rts. Análisis de series temporales de ráster (por ejemplo, series temporales de imágenes de satélite). Sae2. Modelos de series temporales para la estimación de áreas pequeñas. SpTimer. Modelización bayesiana espacio-temporal. vigilancia. Modelado temporal y espacio-temporal y seguimiento de fenómenos epidémicos. TED. Turbulencia de la serie temporal Detección y clasificación de eventos. Mareas Funciones para calcular características de series temporales cuasi periódicas, p. Niveles estuarinos de agua observados. Tigre. Los grupos resueltos temporalmente de las diferencias típicas (errores) entre dos series temporales son determinados y visualizados. TSMining. Minería de motivos univariados y multivariados en datos de series de tiempo. TsModel. Modelado de series temporales para la contaminación del aire y la salud. Paquetes CRAN: Enlaces relacionados: Referencia ILE RPG de WebSphere (R) Development Studio Además, algunos tipos de datos permiten diferentes formatos de datos. Este capítulo describe la diferencia entre formatos de datos internos y externos, describe cada formato y cómo especificarlos. Los campos numérico, de carácter, fecha, hora y sello de hora tienen un formato interno que es independiente del formato externo. El formato interno es la forma en que los datos se almacenan en el programa. El formato externo es la forma en que los datos se almacenan en los archivos. Es necesario tener en cuenta el formato interno cuando: Paso de parámetros por referencia Superposición de subcampos en estructuras de datos Además, es posible que desee considerar el formato interno de campos numéricos, cuando el rendimiento en tiempo de ejecución de las operaciones aritméticas es importante. Para obtener más información, vea Consideraciones sobre el rendimiento. Existe un formato interno y externo predeterminado para los tipos de datos numéricos y de fecha y hora. Puede especificar un formato interno para un campo específico en una especificación de definición. Del mismo modo, puede especificar un formato externo para un campo descrito en el programa en la especificación de entrada o salida correspondiente. Para los campos de un archivo descrito externamente, el formato de datos externo se especifica en las especificaciones de descripción de datos en la posición 35. No se puede cambiar el formato externo de los campos descritos externamente, con una excepción. Si especifica EXTBININT en una especificación de control, cualquier campo binario con posiciones decimales cero se considerará que tiene un formato externo entero. Para los subcampos en estructuras de datos descritas externamente, los formatos de datos especificados en la descripción externa se utilizan como formatos internos de los subcampos por el compilador. El formato interno predeterminado para los campos numéricos independientes es decimal empacado. El formato interno predeterminado para los subcampos de estructura de datos numéricos es zonal-decimal. Para especificar un formato interno diferente, especifique el formato deseado en la posición 40 en la especificación de definición para el campo o subcampo. El formato predeterminado para los campos de fecha, hora y fecha y hora es ISO. En general, se recomienda utilizar el formato interno ISO predeterminado, especialmente si tiene una mezcla de tipos de formato externo. Para los campos de fecha, hora y fecha, puede utilizar las palabras clave DATFMT y TIMFMT en la especificación de control para cambiar el formato interno predeterminado, si lo desea, para todos los campos de fecha y hora del programa. Puede utilizar la palabra clave DATFMT o TIMFMT en una especificación de definición para sustituir el formato interno predeterminado de un campo de fecha y hora individual. Si tiene campos numéricos, de carácter o de fecha y hora en archivos descritos en el programa, puede especificar su formato externo. El formato externo no afecta la forma en que se procesa un campo. Sin embargo, es posible que pueda mejorar el rendimiento de las operaciones aritméticas, dependiendo del formato interno especificado. Para obtener más información, vea Consideraciones sobre el rendimiento. La siguiente tabla muestra cómo especificar el formato externo de los campos descritos por el programa. Para obtener más información sobre cada tipo de formato, consulte la sección correspondiente en el resto de este capítulo. P decimal empacado S Zoned decimal El formato externo predeterminado para los datos numéricos de flotación se denomina representación de pantalla externa. El formato para los datos de flotante de 4 bytes es: El formato para los datos de flotador de 8 bytes es: Tenga en cuenta que un valor de flotador de 4 bytes ocupa 14 posiciones y un valor de flotador de 8 bytes ocupa 23 posiciones. Para datos numéricos que no sean float, el formato externo predeterminado es zonal decimal. El formato externo para los arrays y tablas de tiempo de compilación debe ser zoned-decimal, left-sign o right-sign. Para los arrays y las tablas de tiempo de compilación de flotador, los datos de tiempo de compilación se especifican como literal numérico o literal flotante. Cada elemento de una matriz de flotador de 4 bytes requiere 14 posiciones en el registro de origen cada elemento de una matriz de flotador de 8 bytes requiere 23 posiciones. Los campos numéricos no flotantes definidos en especificaciones de entrada, especificaciones de cálculo o especificaciones de salida sin definición correspondiente en una especificación de definición se almacenan internamente en formato decimal empacado. Para cualquiera de los campos de entrada y salida de la Tabla 11. especifique uno de los siguientes formatos de datos externos válidos: A Caracteres (válidos para caracteres e indicadores) N Indicadores (válidos para caracteres e indicadores) G Gráfico (válido para datos gráficos) C UCS-2 (válido para datos UCS-2) La palabra clave EXTFMT se puede utilizar para especificar los datos de una matriz o tabla en formato UCS-2. Especifique el atributo de datos VAR en las posiciones 31-34 en una especificación de entrada y en las posiciones 53-80 en una especificación de salida para caracteres de longitud variable, gráficos o datos UCS-2. Si tiene campos de fecha, hora y marca de hora en los archivos descritos en el programa, debe especificar su formato externo. Puede especificar un formato externo predeterminado para todos los campos de fecha, hora y marca de hora en un archivo descrito en el programa utilizando las palabras clave DATFMT y TIMFMT en una especificación de descripción de archivo. También puede especificar un formato externo para un campo en particular. Especifique el formato deseado en las posiciones 31-34 en una especificación de entrada. Especifique la palabra clave y el formato adecuados en las posiciones 53-80 en una especificación de salida. Para obtener más información sobre cada tipo de formato, consulte la sección correspondiente en el resto de este capítulo. El tipo de datos de caracteres representa los valores de los caracteres y puede tener cualquiera de los siguientes formatos: Los datos de caracteres pueden contener uno o más caracteres de un solo byte o doble byte, dependiendo del formato especificado. Los campos de caracteres, gráficos y UCS-2 también pueden tener un formato fijo o de longitud variable. La siguiente tabla resume los diferentes formatos de tipo de datos de caracteres. Tipo de datos de caracteres Número de bytes El formato de caracteres de longitud fija es uno o más bytes de longitud definida. Defina un campo de caracteres especificando A en la entrada Tipo de datos de la especificación adecuada. You can also define one using the LIKE keyword on the definition specification where the parameter is a character field. The default initialization value is blanks. The indicator format is a special type of character data. Indicators are all one byte long and can only contain the character values 0 (off) and 1 (on). They are generally used to indicate the result of an operation or to condition (control) the processing of an operation. The default value of indicators is 0. You define an indicator field by specifying N in the Data-Type entry of the appropriate specification. You can also define an indicator field using the LIKE keyword on the definition specification where the parameter is an indicator field. Indicator fields are also defined implicitly with the COMMIT keyword on the file description specification. A special set of predefined RPG IV indicators (INxx) is also available. For a description of these indicators, see RPG IV Indicators. The rules for defining indicator variables are: Indicators can be defined as standalone fields, subfields, prototyped parameters, and procedure return values. If an indicator variable is defined as a prerun-time or compile-time array or table, the initialization data must consist of only 0s and 1s. Note: If an indicator contains a value other than 0 or 1 at runtime, the results are unpredictable. If the keyword INZ is specified, the value must be one of 0, OFF, 1, or ON. The keyword VARYING cannot be specified for an indicator field. The rules for using indicator variables are: The default initialization value for indicator fields is 0. Operation code CLEAR sets an indicator variable to 0. Blank-after function applied to an indicator variable sets it to 0. If an array of indicators is specified as the result of a MOVEA(P) operation, the padding character is 0. Indicators are implicitly defined with ALTSEQ(NONE). This means that the alternate collating sequence is not used for comparisons involving indicators. Indicators may be used as key-fields where the external key is a character of length 1. The graphic format is a character string where each character is represented by 2 bytes. Fields defined as graphic data do not contain shift-out (SO) or shift-in (SI) characters. The difference between single byte character and double byte graphic data is shown in the following figure: The length of a graphic field, in bytes, is two times the number of graphic characters in the field. The fixed-length graphic format is a character string with a set length where each character is represented by 2 bytes. You define a graphic field by specifying G in the Data-Type entry of the appropriate specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a graphic field. The default initialization value for graphic data is X4040. The value of HIVAL is XFFFF, and the value of LOVAL is X0000. The Universal Character Set (UCS-2) format is a character string where each character is represented by 2 bytes. This character set can encode the characters for many written languages. Fields defined as UCS-2 data do not contain shift-out (SO) or shift-in (SI) characters. The length of a UCS-2 field, in bytes, is two times the number of UCS-2 characters in the field. The fixed-length UCS-2 format is a character string with a set length where each character is represented by 2 bytes. You define a UCS-2 field by specifying C in the Data-Type entry of the appropriate specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a UCS-2 field. The default initialization value for UCS-2 data is X0020. The value of HIVAL is XFFFF, LOVAL is X0000, and the value of BLANKS is X0020. For more information on the UCS-2 format, see the iSeries Information Center globalization topic. Variable-length character fields have a declared maximum length and a current length that can vary while a program is running. The length is measured in single bytes for the character format and in double bytes for the graphic and UCS-2 formats. The storage allocated for variable-length character fields is 2 bytes longer than the declared maximum length. The leftmost 2 bytes are an unsigned integer field containing the current length in characters, graphic characters or UCS-2 characters. The actual character data starts at the third byte of the variable-length field. Figure 80 shows how variable-length character fields are stored: Figure 81 shows how variable-length graphic fields are stored. UCS-2 fields are stored similarly. You define a variable-length character data field by specifying A (character), G (graphic), or C (UCS-2) and the keyword VARYING on a definition specification. It can also be defined using the LIKE keyword on a definition specification where the parameter is a variable-length character field. You can refer to external variable-length fields, on an input or output specification, with the VAR data attribute. A variable-length field is initialized by default to have a current length of zero. The following rules apply when defining variable-length fields: The declared length of the field can be from 1 to 65535 single-byte characters and from 1 to 16383 double-byte graphic or UCS-2 characters. The current length may be any value from 0 to the maximum declared length for the field. The field may be initialized using keyword INZ. The initial value is the exact value specified and the initial length of the field is the length of the initial value. The field is padded with blanks for initialization, but the blanks are not included in the length. In all cases except subfields defined using positional notation, the length entry (positions 33-39 on the definition specifications) contains the maximum length of the field not including the 2-byte length. For subfields defined using positional notation, the length includes the 2-byte length. As a result, a variable-length subfield may be 32769 single bytes long or 16384 double bytes long for an unnamed data structure. The keyword VARYING cannot be specified for a data structure. For variable-length prerun-time arrays, the initialization data in the file is stored in variable format, including the 2-byte length prefix. Since prerun-time array data is read from a file and files have a maximum record length of 32766, variable-length prerun-time arrays have a maximum size of 32764 single-byte characters, or 16382 double-byte graphic or UCS-2 characters. A variable-length array or table may be defined with compile-time data. The trailing blanks in the field of data are not significant. The length of the data is the position of the last non-blank character in the field. This is different from prerun-time initialization since the length prefix cannot be stored in compile-time data. LIKE DEFINE cannot be used to define a field like a variable-length field. The following is an example of defining variable-length character fields: The following is an example of defining variable-length graphic and UCS-2 fields: The default initialization value for numeric fields is zero. Binary format means that the sign (positive or negative) is in the leftmost bit of the field and the numeric value is in the remaining bits of the field. Positive numbers have a zero in the sign bit negative numbers have a one in the sign bit and are in twos complement form. A binary field can be from one to nine digits in length and can be defined with decimal positions. If the length of the field is from one to four digits, the compiler assumes a binary field length of 2 bytes. If the length of the field is from five to nine digits, the compiler assumes a binary field length of 4 bytes. Every input field read in binary format is assigned a field length (number of digits) by the compiler. A length of 4 is assigned to a 2-byte binary field a length of 9 is assigned to a 4-byte binary field, if the field is not defined elsewhere in the program. Because of these length restrictions, the highest decimal value that can be assigned to a 2-byte binary field is 9999 and the highest decimal value that can be assigned to a 4-byte binary field is 999 999 999. In general, a binary field of n digits can have a maximum value of n 9s. This discussion assumes zero decimal positions. Because a 2-byte field in binary format is converted by the compiler to a decimal field with 1 to 4 digits, the input value may be too large. If it is, the leftmost digit of the number is dropped. For example, if a four digit binary input field has a binary value of hexadecimal 6000, the compiler converts this to 24 576 in decimal. The 2 is dropped and the result is 4576. Similarly, the input value may be too large for a 4-byte field in binary format. If the binary fields have zero (0) decimal positions, then you can avoid this conversion problem by defining integer fields instead of binary fields. Note: Binary input fields cannot be defined as match or control fields. The number of digits of a binary field is exactly the same as the length in the DDS description. For example, if you define a binary field in your DDS specification as having 7 digits and 0 decimal positions, the RPG IVcompiler handles the data like this: The field is defined as a 4-byte binary field in the input specification A Packed(7,0) field is generated for the field in the RPG IV program. If you want to retain the complete binary field information, redefine the field as a binary subfield in a data structure or as a binary stand-alone field. Note that an externally described binary field may have a value outside of the range allowed by RPG IV binary fields. If the externally described binary field has zero (0) decimal positions then you can avoid this problem. To do so, you define the externally described binary field on a definition specification and specify the EXTBININT keyword on the control specification. This will change the external format of the externally described field to that of a signed integer. The float format consists of two parts: the mantissa and the exponent. The value of a floating-point field is the result of multiplying the mantissa by 10 raised to the power of the exponent. For example, if 1.2345 is the mantissa and 5 is the exponent then the value of the floating-point field is: You define a floating-point field by specifying F in the data type entry of the appropriate specification. The decimal positions must be left blank. However, floating-point fields are considered to have decimal positions. As a result, float variables may not be used in any place where a numeric value without decimal places is required, such as an array index, do loop index, etc. The default initialization and CLEAR value for a floating point field is 0E0. The length of a floating point field is defined in terms of the number of bytes. It must be specified as either 4 or 8 bytes. The range of values allowed for a floating-point field are: 4-byte float (8 digits) -3.4028235E38 to -1.1754944E-38, 0.0E0, 1.1754944E-38 to 3.4028235E38 8-byte float (16 digits) -1.797693134862315E308 to -2.225073858507201E-308, 0.0E0, 2.225073858507201E-308 to 1.797693134862315E308 Note: Float variables conform to the IEEE standard as supported by the OS/400 operating system. Since float variables are intended to represent scientific values, a numeric value stored in a float variable may not represent the exact same value as it would in a packed variable. Float should not be used when you need to represent numbers exactly to a specific number of decimal places, such as monetary amounts. See Specifying an External Format for a Numeric Field for a general description of external display representation. The external display representation of float values applies for the following: Output of float data with Data-Format entry blank. Input of float data with Data-Format entry blank. External format of compile-time and prerun-time arrays and tables (when keyword EXTFMT is omitted). Display and input of float values using operation code DSPLY. Output of float values on a dump listing. Result of built-in function EDITFLT. When outputting float values, the external representation uses a format similar to float literals, except that: Values are always written with the character E and the signs for both mantissa and exponent. Values are either 14 or 23 characters long (for 4F and 8F respectively). Values are normalized. That is, the decimal point immediately follows the most significant digit. The decimal separator character is either period or comma depending on the parameter for Control Specification keyword DECEDIT. Here are some examples of how float values are presented: When inputting float values, the value is specified just like a float literal. The value does not have to be normalized or adjusted in the field. When float values are defined as array/table initialization data, they are specified in fields either 14 or 23 characters long (for 4F and 8F respectively). Note the following about float fields: Alignment of float fields may be desired to improve the performance of accessing float subfields. You can use the ALIGN keyword to align float subfields defined on a definition specification. 4-byte float subfields are aligned on a 4-byte boundary and 8-byte float subfields are aligned along a 8-byte boundary. For more information on aligning float subfields, see ALIGN. Length adjustment is not allowed when the LIKE keyword is used to define a field like a float field. Float input fields cannot be defined as match or control fields. The integer format is similar to the binary format with two exceptions: The integer format allows the full range of binary values The number of decimal positions for an integer field is always zero. You define an integer field by specifying I in the Data-Type entry of the appropriate specification. You can also define an integer field using the LIKE keyword on a definition specification where the parameter is an integer field. The length of an integer field is defined in terms of number of digits it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage a 5-digit field takes up 2 bytes of storage a 10-digit field takes up 4 bytes a 20-digit field takes up 8 bytes. The range of values allowed for an integer field depends on its length. Field length Range of Allowed Values 3-digit integer -128 to 127 5-digit integer -32768 to 32767 10-digit integer -2147483648 to 2147483647 20-digit integer -9223372036854775808 to 9223372036854775807 Note the following about integer fields: Alignment of integer fields may be desired to improve the performance of accessing integer subfields. You can use the ALIGN keyword to align integer subfields defined on a definition specification. 2-byte integer subfields are aligned on a 2-byte boundary 4-byte integer subfields are aligned along a 4-byte boundary 8-byte integer subfields are aligned along an 8-byte boundary. For more information on aligning integer subfields, see ALIGN. If the LIKE keyword is used to define a field like an integer field, the Length entry may contain a length adjustment in terms of number of digits. The adjustment value must be such that the resulting number of digits for the field is 3, 5, 10, or 20. Integer input fields cannot be defined as match or control fields. Packed-decimal format means that each byte of storage (except for the low order byte) can contain two decimal numbers. The low-order byte contains one digit in the leftmost portion and the sign (positive or negative) in the rightmost portion. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. The packed-decimal format looks like this: The sign portion of the low-order byte indicates whether the numeric value represented in the digit portions is positive or negative. Figure 89 shows what the decimal number 21544 looks like in packed-decimal format. Use the following formula to find the length in digits of a packed-decimal field: This formula gives you the maximum number of digits you can represent in packed-decimal format the upper limit is 31. Packed fields can be up to 16 bytes long. Table 12 shows the packed equivalents for zoned-decimal fields up to 31 digits long: Zoned-Decimal Length in Digits Number of Bytes Used in Packed-Decimal Field For example, an input field read in packed-decimal format has a length of five bytes (as specified on the input or definition specifications). The number of digits in this field equals 2(5) - 1 or 9. Therefore, when the field is used in the calculation specifications, the result field must be nine positions long. The PACKEVEN keyword on the definition specification can be used to indicate which of the two possible sizes you want when you specify a packed subfield using from and to positions rather than number of digits. The unsigned integer format is like the integer format except that the range of values does not include negative numbers. You should use the unsigned format only when non-negative integer data is expected. You define an unsigned field by specifying U in the Data-Type entry of the appropriate specification. You can also define an unsigned field using the LIKE keyword on the definition specification where the parameter is an unsigned field. The length of an unsigned field is defined in terms of number of digits it can be 3, 5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage a 5-digit field takes up 2 bytes of storage a 10-digit field takes up 4 bytes a 20-digit field takes up 8 bytes. The range of values allowed for an unsigned field depends on its length. Field length Range of Allowed Values 3-digit unsigned 0 to 255 5-digit unsigned 0 to 65535 10-digit unsigned 0 to 4294967295 20-digit unsigned 0 to 18446744073709551615 For other considerations regarding the use of unsigned fields, including information on alignment, see Integer Format. Zoned-decimal format means that each byte of storage can contain one digit or one character. In the zoned-decimal format, each byte of storage is divided into two portions: a 4-bit zone portion and a 4-bit digit portion. The zoned-decimal format looks like this: The zone portion of the low-order byte indicates the sign (positive or negative) of the decimal number. The standard signs are used: hexadecimal F for positive numbers and hexadecimal D for negative numbers. In zoned-decimal format, each digit in a decimal number includes a zone portion however, only the low-order zone portion serves as the sign. Figure 89 shows what the number 21544 looks like in zoned-decimal format. You must consider the change in field length when coding the end position in positions 40 through 43 of the Output specifications and the field is to be output in packed format. To find the length of the field after it has been packed, use the following formula: You can specify an alternative sign format for zoned-decimal format. In the alternative sign format, the numeric field is immediately preceded or followed by a or - sign. A plus sign is a hexadecimal 4E, and a minus sign is a hexadecimal 60. When an alternative sign format is specified, the field length (specified on the input specification) must include an additional position for the sign. For example, if a field is 5 digits long and the alternative sign format is specified, a field length of 6 positions must be specified. Keep in mind the following when defining numeric fields: When coding the end position in positions 47 through 51 of the output specifications, be sure to use the external format when calculating the number of bytes to be occupied by the output field. For example, a packed field with 5 digits is stored in 3 bytes, but when output in zoned format, it requires 5 bytes. When output in integer format, it only requires 2 bytes. If you move a character field to a zoned numeric, the sign of the character field is fixed to zoned positive or zoned negative. The zoned portion of the other bytes will be forced to F. However, if the digit portion of one of the bytes in the character field does not contain a valid digit a decimal data error will occur. When numeric fields are written out with no editing, the sign is not printed as a separate character the last digit of the number will include the sign. This can produce surprising results for example, when -625 is written out, the zoned decimal value is XF6F2D5 which appears as 62N. You should specify the integer or unsigned format for fields when: Performance of arithmetic is important With certain arithmetic operations, it may be important that the value used be an integer. Some examples where performance may be improved include array index computations and arguments for the built-in function SUBST. Interacting with routines written in other languages that support an integer data type, such as ILE C. Using fields in file feedback areas that are defined as integer and that may contain values above 9999 or 999999999. Packed, zoned, and binary formats should be specified for fields when: Using values that have implied decimal positions, such currency values Manipulating values having more than 19 digits Ensuring a specific number of digits for a field is important Float format should be specified for fields when: The same variable is needed to hold very small and/or very large values that cannot be represented in packed or zoned values. Note: Overflow is more likely to occur with arithmetic operations performed using the integer or unsigned format, especially when integer arithmetic occurs in free-form expressions. This is because the intermediate results are kept in integer or unsigned format rather than a temporary decimal field of sufficient size. Figure 89 shows what the decimal number 21544 looks like in various formats. Note the following about the representations in the figure. To obtain the numeric value of a positive binary or integer number, unsigned number, add the values of the bits that are on (1), but do not include the sign bit (if present). For an unsigned number, add the values of the bits that are on, including the leftmost bit. The value 21544 cannot be represented in a 2-byte binary field even though it only uses bits in the low-order two bytes. A 2-byte binary field can only hold up to 4 digits, and 21544 has 5 digits. Figure 90 shows the number -21544 in integer format. Date fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all date data. Date constants or variables used in comparisons or assignments do not have to be in the same format or use the same separators. Also, dates used for I/O operations such as input fields, output fields or key fields are also converted (if required) to the necessary format for the operation. The default internal format for date variables is ISO. This default internal format can be overridden globally by the control specification keyword DATFMT and individually by the definition specification keyword DATFMT. The hierarchy used when determining the internal date format and separator for a date field is From the DATFMT keyword specified on the definition specification From the DATFMT keyword specified on the control specification ISO There are three kinds of date data formats, depending on the range of years that can be represented. This leads to the possibility of a date overflow or underflow condition occurring when the result of an operation is a date outside the valid range for the target field. The formats and ranges are as follows: Number of Digits in Year 2 (YMD, DMY, MDY, JUL) Several formats are also supported for fields used by the MOVE, MOVEL, and TEST operations only. This support is provided for compatibility with externally defined values that are already in a 3-digit year format and the 4-digit year LONGJUL format. It also applies to the 2-digit year formats when JOBRUN is specified. JOBRUN should be used when the field which it is describing is known to have the attributes from the job. For instance, a 12-digit numeric result of a TIME operation will be in the job date format. Table 15 lists the valid externally defined date formats that can be used in Factor 1 of a MOVE, MOVEL, and TEST operation. Format (Default Separator) 2-Digit Year Formats Determined at runtime from the DATFMT, or DATSEP job values. 3-Digit Year Formats 2 4-Digit Year Formats JOBRUN is valid only for character or numeric dates with a 2-digit year since the run-time job attribute for DATFMT can only be MDY, YMD, DMY or JUL. Valid values for the century character c are: When coding a date format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code date formats without separators see MOVE (Move). MOVEL (Move Left) and TEST (Test Date/Time/Timestamp). To initialize the Date field to the system date at runtime, specify INZ(SYS) on the definition specification. To initialize the Date field to the job date at runtime, specify INZ(JOB) on the definition specification. SYS or JOB cannot be used with a field that is exported. The Date field can also be initialized to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. Time fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all time data. Time constants or variables used in comparisons or assignments do not have to be in the same format or use the same separators. Also, times used for I/O operations such as input fields, output fields or key fields are also converted (if required) to the necessary format for the operation. The default internal format for time variables is ISO. This default internal format can be overridden globally by the control specification keyword TIMFMT and individually by the definition specification keyword TIMFMT. The hierarchy used when determining the internal time format and separator for a time field is From the TIMFMT keyword specified on the definition specification From the TIMFMT keyword specified on the control specification ISO Table 16 shows the time formats supported and their separators. RPG Format Name When coding a time format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify the format followed by a zero. For more information on how to code time formats without separators see MOVE (Move). To initialize the Time field to the system time at runtime, specify INZ(SYS) on the definition specification. SYS cannot be used with a field that is exported. The Time field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. A special value of JOBRUN can be used in Factor 1 of a MOVE, MOVEL or TEST operation. This indicates that the separator of the field being described is based on the run-time job attributes, TIMSEP. Timestamp fields have a predetermined size and format. They can be defined on the definition specification. Timestamp data must be in the format Microseconds (.mmmmmm) are optional for timestamp literals and if not provided will be padded on the right with zeros. Leading zeros are required for all timestamp data. The default initialization value for a timestamp is midnight of January 1, 0001 (0001-01-01-00.00.00.000000). The HIVAL value for a timestamp is 9999-12-31-24.00.00.000000. The LOVAL value for timestamp is 0001-01-01-00.00.00.000000. When coding the timestamp format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators, specify ISO0. For an example of how ISO is used without separators see TEST (Test Date/Time/Timestamp). To initialize the Timestamp field to the system date at runtime, specify INZ(SYS) on the definition specification. SYS cannot be used with a field that is exported. The Timestamp field can also be initialized at runtime to a literal, named constant or figurative constant. Note: Runtime initialization takes place after static intitialization. The object data type allows you to define a Java object. You specify the object data type as follows: In position 40, you specify data type O. In the keyword section, you specify the CLASS keyword to indicate the class of the object. Specify JAVA for the environment, and the class name. If the object is the return type of a Java constructor, the class of the returned object is the same as the class of the method so you do not specify the CLASS keyword. Instead, you specify the EXTPROC keyword with environment JAVA, the class name, and procedure name CONSTRUCTOR. An object cannot be based. It also cannot be a subfield of a data structure. If an object is an array or table, it must be loaded at runtime. Pre-run and compile-time arrays and tables of type Object are not allowed. Every object is initialized to NULL, which means that the object is not associated with an instance of its class. To change the contents of an object, you must use method calls. You cannot directly access the storage used by the object. Classes are resolved at runtime. The compiler does not check that a class exists or that it is compatible with other objects. You can use an object field in the following situations: Free-Form Evaluation You can use the EVAL operation to assign one Object item (field or prototyped procedure) to a field of type Object. Free-Form Comparison You can compare one object to another object. You can specify any comparison, but only the following comparisons are meaningful: Equality or inequality with another object. Two objects are equal only if they represent exactly the same object. Two different objects with the same value are not equal. If you want to test for equality of the value of two objects, use the Java equals method as follows: Equality or inequality with NULL. An object is equal to NULL if it is not associated with a particular instance of its class. Free-Form Call Parameter You can code an object as a parameter in a call operation if the parameter in the prototype is an object. Objects are not valid as input or output fields. Assignment validity is not checked. For example, RPG would allow you to assign an object of class Number to an object variable defined with class String. If this was not correct, a Java error would occur when you tried to use the String variable. Basing pointers are used to locate the storage for based variables. The storage is accessed by defining a field, array, or data structure as based on a particular basing pointer variable and setting the basing pointer variable to point to the required storage location. For example, consider the based variable MYFIELD, a character field of length 5, which is based on the pointer PTR1. The based variable does not have a fixed location in storage. You must use a pointer to indicate the current location of the storage for the variable. Suppose that the following is the layout of some area of storage: If we set pointer PTR1 to point to the G, If MYFIELD is now changed by an EVAL statement to HELLO, the storage starting at the J would change: Use the BASED keyword on the definition specification (see BASED(basingpointername) ) to define a basing pointer for a field. Basing pointers have the same scope as the based field. The length of the basing pointer field must be 16 bytes long and must be aligned on a 16 byte boundary. This requirement for boundary alignment can cause a pointer subfield of a data structure not to follow the preceding field directly, and can cause multiple occurrence data structures to have non-contiguous occurrences. For more information on the alignment of subfields, see Aligning Data Structure Subfields. The default initialization value for basing pointers is NULL. Note: When coding basing pointers, you must be sure that you set the pointer to storage that is large enough and of the correct type for the based field. Figure 96 shows some examples of how not to code basing pointers. Note: You can add or subtract an offset from a pointer in an expression, for example EVAL ptr ptr offset. When doing pointer arithmetic be aware that it is your responsibility to ensure that you are still pointing within the storage of the item you are pointing to. In most cases no exception will be issued if you point before or after the item. When subtracting two pointers to determine the offset between them, the pointers must be pointing to the same space, or the same type of storage. For example, you can subtract two pointers in static storage, or two pointers in automatic storage, or two pointers within the same user space. You set or change the location of the based variable by setting or changing the basing pointer in one of the following ways: Initializing with INZ(ADDR(FLD)) where FLD is a non-based variable Assigning the pointer to the result of ADDR(X) where X is any variable Assigning the pointer to the value of another pointer Using ALLOC or REALLOC (see ALLOC (Allocate Storage). REALLOC (Reallocate Storage with New Length). and the WebSphere Development Studio: ILE RPG Programmers Guide for examples) Moving the pointer forward or backward in storage using pointer arithmetic: (offset is the distance in bytes that the pointer is moved)Section Menu Welcome Background to BUGS The BUGS ( B ayesian inference U sing G ibbs S ampling) project is concerned with flexible software for the Bayesian analysis of complex statistical models using Markov chain Monte Carlo (MCMC) methods. The project began in 1989 in the MRC Biostatistics Unit, Cambridge, and led initially to the Classic BUGS program, and then onto the WinBUGS software developed jointly with the Imperial College School of Medicine at St Marys, London. Development is now focussed on the OpenBUGS project. WinBUGS 1.4.3 This site at the MRC Biostatistics Unit is primarily concerned with the stand-alone WinBUGS 1.4.3 package. Features a graphical user interface and on-line monitoring and convergence diagnostics. Over 30000 downloads, and a huge number of applications and links. WinBUGS development site includes facilities to add distributions, functions, and includes add-ons for pharmacokinetic modelling, differential equations, and reversible jump MCMC. Can be called from R with R2WinBUGS . WinBUGS 1.4.3 is a stable version which is recommended for standard use. However many developments are now taking place using OpenBUGS. Note: The preferred reference for citing WinBUGS in scientific papers is: Lunn, D. J. Thomas, A. Best, N. and Spiegelhalter, D. (2000) WinBUGS -- a Bayesian modelling framework: concepts, structure, and extensibility. Statistics and Computing . 10 :325--337. OpenBUGS The OpenBUGS project can be found here . Open-source version of the core BUGS code with a variety of interfaces. Runs under Windows with a very similar graphical interface to WinBUGS. Runs on Linux with a plain-text interface. Can be embedded in R as BRugs . Different architecture from WinBUGS 1.4.3: this means that WinBUGS 1.4 add-ons on the WinBUGS development site will not yet run in OpenBUGS. OpenBUGS is the main development platform and is currently experimental, but will eventually become the standard version. The aim is then to transfer new 1.4 functionality to OpenBUGS. Similar software JAGS (Just Another Gibbs Sampler) by Martyn Plummer is an open source program which was developed independently of the BUGS project. JAGS uses essentially the same model description language, but it has been completely re-written. This runs natively on Windows, Mac, Linux and several other varieties of Unix. Stan is another program for general Bayesian analysis, developed even more recently at Columbia University. It uses a modelling language inspired by BUGS and superficially similar, but it is conceptually different in many ways. NIMBLE can also be used to fit general models written in the BUGS language, and includes the ability to write novel sampling algorithms. Health warning The programs are reasonably easy to use and come with a wide range of examples. There is, however, a need for caution. A knowledge of Bayesian statistics is assumed, including recognition of the potential importance of prior distributions, and MCMC is inherently less robust than analytic statistical methods. There is no in-built protection against misuse. copy2016 MRC Biostatistics Unit. Cambridge Biomedical Campus. Cambridge Institute of Public Health. Forvie Site. Robinson Way. Cambridge CB2 0SR. UK. 01223 330366

No comments:

Post a Comment