3

我从文本文件中导入了 R 中的 4 列和 1180598 行数据。以下是前五行数据:

  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

上面最左边的列是索引。“车辆 ID”是特定“时间”的车辆 ID,如“时间”列中所示。总共有 2169 辆车,但这里只显示了第 2 辆车。'Vehicle Class' 可以是 1 = 摩托车、2 = 汽车或 3 = 卡车。在上面显示的数据中,它是汽车。“前车”是“车辆ID”栏中提到的前车的车辆ID。

我想使用上面的信息创建一个新的“先前车辆类别”列。对于 R 查找 Preceding Vehicle Class,它必须首先查看“Preceding Vehicle”列,然后查看“Vehicle ID”列,当它找到相同的 ID 时,它应该在“Vehicle Class”中看到车辆的类别列并将结果存储在新列“先前车辆类别”中。我尝试了以下代码,但加载时间超过 5 分钟,没有任何反应:

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' 是数据框的名称。请帮助修复代码。

4

2 回答 2

3

使用以下版本a

a <- structure(list(VehicleID = c(0L, 0L, 2L, 2L), Time = c(0.1, 0.2, 0.4, 0.5), VehicleClass = c(8L, 8L, 2L, 2L), PrecedingVehicle = c(-1L, -1L, 0L, 0L)), .Names = c("VehicleID", "Time", "VehicleClass", "PrecedingVehicle"), class = "data.frame", row.names = c("1", "2", "9", "10"))

看起来像:

   VehicleID Time VehicleClass PrecedingVehicle
1          0  0.1            8               -1
2          0  0.2            8               -1
9          2  0.4            2                0
10         2  0.5            2                0

你可以这样做:

a$PrecVehClass <- a$VehicleClass[match(a$PrecedingVehicle,a$VehicleID)]

这会给你你想要的结果:

   VehicleID Time VehicleClass PrecedingVehicle PrecVehClass
1          0  0.1            8               -1           NA
2          0  0.2            8               -1           NA
9          2  0.4            2                0            8
10         2  0.5            2                0            8
于 2013-09-30T05:42:36.350 回答
1

如thelatemaila的回答所示:

new_a = merge(a, a[, c('VehicleID', 'VehicleClass')], 
              by.x='PrecedingVehicle',
              by.y='VehicleID', 
              all.x=TRUE)

names(new_a) = c("PrecedingVehicle" ,"VehicleID","Time","VehicleClass",
             "Preceding Vehicle Class")

所有处理实际上都是merge在第一行完成的。我只是没有找到更优雅的方式来处理列的重命名......

如果您熟悉 SQL,那么这就是左外自连接。

于 2013-09-30T06:06:39.793 回答