简体   繁体   中英

Time Series date format DD:mm:yy HH:mm:ss to DD:mm:yy in R

My date column gives me NA values when I try to change the time series date format.

DATASET :

     Date   IIP   CPI Term.Spread RealMoney    NSE50 CallMoneyRate
1 2013:01:00 107.2 104.6   -0.059420  81740.83 6023.117      8.001140
2 2013:02:00 101.4 105.3    0.119139  83898.19 5893.587      7.804981
3 2013:03:00 115.2 105.5    0.110670  85029.03 5782.261      7.899530
4 2013:04:00 102.6 106.1    0.262090  86276.79 5699.760      7.525810
5 2013:05:00 106.0 106.9    0.189202  87405.71 6064.522      7.291098
6 2013:06:00 101.3 109.3    0.220076  87329.72 5782.078      7.240324
#------> importing all libraries

library("lubridate")
# install.packages("forecast")
# install.packages("ggplot2")
library('ggplot2')
library('fpp')
library('forecast')
library('tseries')
# install.packages("vars")
library(xts)


#--------->reading data
inputData <- read.csv("C:/Users/sanat/Downloads/exercise_1.csv",         header=T)
inputData$logIIP <- log(inputData$IIP)
head(inputData)

inputData$logCPI <- log(inputData$CPI)
head(inputData)
inputData$CPI <- NULL
inputData$IIP <- NULL
head(inputData)
inputDate <- ts(start = 2013, end = 2018, frequency = 365)


#inputData$Date <- as.Date(class(inputData$Date), format = "%Y-%m")
#head(inputData)

Area of doubt(output gives NA values)

strptime(inputData$Date, format = "%m-%Y")

My inputData$Date give NA as output. How should i handle the DD-mm-yy hh:mm:ss format. I am a beginner in R.Kindly guide me through.

The reason it is failed is that the date cannot have a value 0 , it is in 1-31 range. To cope a problem you need to change last 0 into 1 , for example using stringr package. Then using lubridate package you can convert it into Date format. Please see below:

# data simulation
Date <- expand.grid(2013:2018, c(paste0("0", 1:9), 10, 11, 12))
inputData <- data.frame(Date = sort(paste0(Date$Var1, ":", Date$Var2, ":", "00")))


# conversion
library(lubridate)
library(stringr)

str_sub(inputData$Date, -1, -1) <- "1"
inputData$Date <- ymd(inputData$Date)


str(inputData)
# 'data.frame': 72 obs. of  1 variable:
#   $ Date: Date, format: "2013-01-01" "2013-02-01" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM