简体   繁体   中英

Time series (xts) strptime; ONLY month and day

I've been trying to do a time series on my dataframe, and I need to strip times from my csv. This is what I've got:

campbell <-read.csv("campbell.csv")

campbell$date = strptime(campbell$date, "%m/%d")
campbell.ts <- xts(campbell[,-1],order.by=campbell[,1])

First, what I'm trying to do is just get xts to strip the dates as "xx/xx" meaning just the month and day. I have no year for my data. When I try that second line of code and call upon the date column, it converts it to "2013-xx-xx." These months and days have no year associated with them, and I can't figure out how to get rid of the 2013. (The csv file I'm calling on has the dates in the format "9/30,10/1...etc.)

Secondly, once I try and make a time series (the third line), I am unsure what the "order.by" command is calling on. What am I indexing?

Any help??

Thanks!

For strptime , you need to provide the full date, ie day, month and year. In case, any of these is not provided, current ones are assumed from the system's time and appended to the incomplete date. So, if you want to retain your date format as you have read it, first make a copy of that and store in a temporary variable and then use strptime over campbell$date to convert into R readable date format. Since, year is not a concern to you, you need not bother about it even though it is automatically appended by strptime .

campbell <-read.csv("campbell.csv")
date <- campbell$date
campbell$date <- strptime(campbell$date, "%m/%d")

Secondly, what you are doing by 'the third line' ( xts(campbell[,-1],order.by=campbell[,1]) ) command is that, your are telling to order all the data of campbell except the first column ( campbell[,-1] ) according to the index provided by the time data in the first column of campbell ( campbell[,1] ). So, it would only work given the date is in the first column.

After ordering the data according to time-series, you can replace back the campbell$date column with date to get back the date format you wanted (although here, first you have to order date also like shown below)

date <- xts(date, order.by=campbell[,1])  # assuming campbell$date is campbell[,1]
campbell.ts <- xts(campbell[,-1], order.by=campbell[,1])
campbell.ts <- cbind(date, campbell.ts)
format(as.Date(campbell$dat, "%m/%d/%Y"), "%m/%d")

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