這裏有幾個的方法:
1)動物園
如果我們使用動物園則計算將是特別簡單表示這是一個時間系列:
# test data with two cars
Lines <- "car lap laptime
1 1 138.523
1 2 122.373
1 3 121.395
1 4 137.871
2 1 138.523
2 2 122.373
2 3 121.395
2 4 137.871"
cat(Lines, "\n", file = "data.txt")
# read it into a zoo series, splitting it
# on car to give wide form (rather than long form)
library(zoo)
z <- read.zoo("data.txt", header = TRUE, split = 1, index = 2, FUN = as.numeric)
# now that its in the right form its simple
zz <- cbind(z, diff(z))
的最後的聲明給出:
> zz
1.z 2.z 1.diff(z) 2.diff(z)
1 138.523 138.523 NA NA
2 122.373 122.373 -16.150 -16.150
3 121.395 121.395 -0.978 -0.978
4 137.871 137.871 16.476 16.476
要繪製zz
,每塊板一列,試試這個:
plot(zz, type = "o")
要只繪製我們並不真正需要zz
在首位的差異,因爲這將做到:
plot(diff(z), type = "o")
(添加screen=1
參數plot
命令繪製在同一面板上的所有內容。)
2)ave。這裏是第二個解決方案,它只使用普通的R(除了繪圖)並保持長輸出;然而,這是一個比較複雜的:
# assume same input as above
DF <- read.table("data.txt", header = TRUE)
DF$diff <- ave(DF$laptime, DF$car, FUN = function(x) c(NA, diff(x)))
結果是:
> DF
car lap laptime diff
1 1 1 138.523 NA
2 1 2 122.373 -16.150
3 1 3 121.395 -0.978
4 1 4 137.871 16.476
5 2 1 138.523 NA
6 2 2 122.373 -16.150
7 2 3 121.395 -0.978
8 2 4 137.871 16.476
要繪製只是差異,每個面板一個,試試這個:
library(lattice)
xyplot(diff ~ lap | car, DF, type = "o")
更新
添加了以上關於繪圖的信息,因爲問題的標題ñ提到這一點。
謝謝 - 是的,最初的計劃是能夠應付第1欄中列出的不同車輛,但我也希望確保明確地提供簡單的案例問答(部分原因是我希望能夠制定出下一步我自己!) – psychemedia