加載和轉換數據:
## data now comma-separated as you have fields containing whitespace
R> res <- read.csv(text="
vehicleId, visitDate, taskName
123, 1/1/2013, Change Battery
456, 1/1/2013, Wiper Blades Changed
123, 1/2/2013, Tire Pressure Check
123, 1/3/2013, Tire Rotation
456, 3/1/2013, Tire Pressure Check", stringsAsFactors=FALSE)
R> res$visitDate <- as.Date(res$visitDate, "%m/%d/%Y") ## now in Daye format
看看:
R> res
vehicleId visitDate taskName
1 123 2013-01-01 Change Battery
2 456 2013-01-01 Wiper Blades Changed
3 123 2013-01-02 Tire Pressure Check
4 123 2013-01-03 Tire Rotation
5 456 2013-03-01 Tire Pressure Check
R>
日期Calcs(計算):
R> res[3,"visitDate"] - res[1,"visitDate"]
Time difference of 1 days
R> as.numeric(res[3,"visitDate"] - res[1,"visitDate"])
[1] 1
R> difftime(res[3,"visitDate"],res[1,"visitDate"], unit="hours")
Time difference of 24 hours
R> as.numeric(difftime(res[3,"visitDate"],res[1,"visitDate"], unit="hours"))
[1] 24
R>
矢量化:
R> as.numeric(difftime(res[2:nrow(res),"visitDate"],
+ res[1:(nrow(res)-1),"visitDate"], unit="hours"))
[1] 0 24 24 1368
R>
你當然也可以指定一個新的列。您也可以通過車輛編號來進行子集劃分。
無效的東西在我的數據集 – user3056186