I have imported 4 columns and 1180598 rows of data in R from a text file. Following are the first five rows of data:
Vehicle ID Time Vehicle Class Preceding Vehicle
1 2 0.1 2 0
2 2 0.2 2 0
3 2 0.3 2 0
4 2 0.4 2 0
5 2 0.5 2 0
The left-most column above is the index. 'Vehicle ID' is the ID of vehicle at a specific 'Time' as shown in 'Time' column. There are 2169 vehicles in total but here only vehicle 2 is shown. 'Vehicle Class' can be 1=motorcycle, 2=car or 3=truck. In the data shown above it is car. 'Preceding Vehicle' is the ID of the vehicle preceding the vehicle mentioned in 'Vehicle ID' column.
I want to create a new column of 'Preceding Vehicle Class' using the information above. For R to find the Preceding Vehicle Class, it must first look in the 'Preceding Vehicle' column and then go to look in 'Vehicle ID' column, when it finds the same ID it should see the class of vehicle in 'Vehicle Class' column and store the result in a new column 'Preceding Vehicle Class'. I have tried following code, but loading time exceeds 5 minutes and nothing happens:
for (i in a[,'Preceding Vehicle']) for (j in a[,'Vehicle ID']) {
if (i==j) {pclass <- a[,'Vehicle ID']} else {pclass <- 0} }
a[,'Preceding Vehicle Class'] <- pclass
'a' is the name of dataframe. Please help fixing the code.