【问题标题】:How to use if else statement in for loop for creating a new column?如何在 for 循环中使用 if else 语句来创建新列?
【发布时间】:2013-10-05 21:18:14
【问题描述】:

我从文本文件中导入了 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 要查找前一车辆类别,它必须首先查看“前一车辆”列,然后转到“车辆 ID”列,当它找到相同的 ID 时,它应该在“车辆类别”中看到车辆的类别列并将结果存储在新列“先前车辆类别”中。我尝试了以下代码,但加载时间超过 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' 是数据框的名称。请帮助修复代码。

【问题讨论】:

    标签: r if-statement for-loop dataframe


    【解决方案1】:

    使用以下版本的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
    

    【讨论】:

      【解决方案2】:

      给定a,如 thelatemail 的回答:

      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,那么这就是左外自连接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多