我想要做的是存储veh.velocity的输出并将其组合到每次迭代的新数据帧y中。我知道最好先设置一个空的数据框,然后在最后合并数据列。不同的迭代也具有不同数量的行。可以只考虑前20个?非常抱歉,如果下面有几个问题和误解,我是几个月前才开始编程的。谢谢
CSV文件:https://drive.google.com/file/d/1tMOz_yM-WenSOlF3UK6UatniwtFI7kzf/view?usp=sharing
#Time series
#This programme evaluates each vehicles speed behaviour w.r.t time.
library(ggplot2)
library(fpc)
library(factoextra)
library(readr)
library(plotly)
library(dplyr)
library(fpp2)
#Clear all variables in workspace
rm(list=ls())
#Importing data
df <- read_csv("01_tracks.csv")
#Preparing data
df1 <- filter(df,laneId == 5, width <= 6) #Filtering to only lane 5 and no trucks
#Creating empty lists
y <- data.frame()
#Loop to plot time series for only filtered vehicle id's
for(i in unique(df1$id)[1:6]) { #Only considering first 6 vehicles for now due to long computation time
print(i) #List of vehicle id's
veh <- filter(df1,id == i) #New dataframe for vehicles/id's which are in lanes 5
timeseries <- ts(veh[,7],start = 1) #Declare as time series data
plot(autoplot(timeseries) + ggtitle(i) + ylab("X Velocity")) #Plotting time series
veh.velocity <- select(veh,xVelocity) #New dataframe for only vehicle id and its velocity
y <- cbind.data.frame(y,veh.velocity)
}
答案 0 :(得分:0)
如果您只想绘制各个车辆ID的时间序列,则不确定是否有必要使用循环。例如,您可以轻松制作一个time
变量并使用ggplot2
进行绘制:
library(dplyr)
library(ggplot2)
df1 %>%
group_by(id) %>%
mutate(time = 1:n()) %>%
ggplot(aes(x = time, y = xVelocity, color = as.factor(id))) +
geom_line(show.legend = FALSE, alpha = 0.5)
您可以使用pivot_wider
中的tidyr
重塑数据:
library(tidyr)
result <- df1 %>%
group_by(id) %>%
mutate(time = 1:n()) %>%
dplyr::select(time, xVelocity) %>%
pivot_wider(id_cols = time, values_from = xVelocity,
names_prefix = "Veh.", names_from = id)
result
# A tibble: 414 x 287
time Veh.1 Veh.3 Veh.7 Veh.11 Veh.12 Veh.14 Veh.15 Veh.25 Veh.31 Veh.47 Veh.50 Veh.53 Veh.55 Veh.59
<int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 40.8 35.7 32.6 24.7 35.8 41.5 35.7 37.9 39.2 39.2 40.3 39.5 33.0 38.2
2 2 40.9 35.7 32.6 24.8 35.8 41.5 35.7 37.9 39.2 39.2 40.3 39.5 33.0 38.2
3 3 40.9 35.7 32.6 24.8 35.8 41.5 35.7 38.0 39.2 39.2 40.3 39.6 33.0 38.2
4 4 40.9 35.7 32.6 24.8 35.8 41.5 35.7 38.0 39.2 39.2 40.3 39.6 33.1 38.2
5 5 40.9 35.7 32.6 24.8 35.8 41.5 35.7 38.0 39.2 39.2 40.3 39.6 33.1 38.1
6 6 40.9 35.7 32.6 24.9 35.8 41.6 35.7 38 39.2 39.2 40.4 39.6 33.1 38.1
7 7 40.9 35.7 32.7 24.9 35.8 41.6 35.7 38.0 39.2 39.2 40.4 39.6 33.1 38.1
8 8 40.9 35.7 32.7 24.9 35.8 41.6 35.7 38.0 39.2 39.3 40.4 39.6 33.1 38.1
9 9 41.0 35.8 32.7 25.0 35.8 41.6 35.7 38.0 39.2 39.3 40.4 39.6 33.1 38.1
10 10 41.0 35.8 32.7 25 35.8 41.6 35.7 38.1 39.2 39.3 40.4 39.7 33.1 38.1
# … with 404 more rows, and 272 more variables: