首页 > 解决方案 > 如何在 R 中修复具有两个条件的 if 语句(它在长度 8 后停止)

问题描述

我正在向我的数据框中添加一列,并尝试使用该列根据两个条件(时间差异和距离量)对数据进行分组。我的代码由用于 50K 观察的 ifelse 语句组成,它可以很好地从第 1 行循环到第 7 行,但它拒绝循环超过长度 8。它没有向我显示错误,所以我想知道,我是否错过了我的代码中有什么?任何帮助是极大的赞赏。

df
j <- 1
df$GroupID <- NA
df$GroupID[1] <- 1
for (i in 2:length(df)) {
  flashes <- df[which(df$GroupID==j)]
  h <- cbind(flashes$Long,flashes$Lat)
  point <- cbind(df$Long[i],df$Lat[i])
  lastrow <- tail(flashes, n = 1)
  moment <- lastrow$DateTime
  
  ifelse (min(spDistsN1(h,point,longlat = TRUE))<16 & 
          difftime(df$DateTime[i],moment)<minutes(15),
          df$GroupID[i] <-j,df$GroupID[i] <-NA)

  #arrange(df[, "GroupID"])
}

j=j+1

我的数据的第一行如下所示:

DateTime Lat Long GroupID
2019-07-01 00:00:04 28.478 81.066 1
2019-07-01 00:00:04 28.479 81.068 1
2019-07-01 00:00:04 28.482 81.066 1
2019-07-01 00:04 28.475 81.085 1
2019-07-01 00:00:04 28.484 81.084 1
2019-07-01 00:00:04 28.492 81.080 1
2019-07-01 00:00:04 28.493 90-701 28.493
90-701 00:00:04 28.493 81.081 1
2019-07-01 00:00:04 28.494 81.078 不适用
2019-07-01 00:00:04 28.495 81.075 不适用 2019-07-01
00:00:075 28.497-1.8 不适用
-01 00:00:04 28.507 81.074 不适用

标签: rloopsif-statementconditional-statements

解决方案


length()data.frame 是它拥有的列数,所以只需nrow()使用

df
j <- 1
df$GroupID <- NA
df$GroupID[1] <- 1
for (i in 1:nrow(df)) {
  flashes <- df[which(df$GroupID==j)]
  h <- cbind(flashes$Long,flashes$Lat)
  point <- cbind(df$Long[i],df$Lat[i])
  lastrow <- tail(flashes, n = 1)
  moment <- lastrow$DateTime
  
  ifelse (min(spDistsN1(h,point,longlat = TRUE))<16 & 
          difftime(df$DateTime[i],moment)<minutes(15),
          df$GroupID[i] <-j,df$GroupID[i] <-NA)

  #arrange(df[, "GroupID"])
}

j=j+1

推荐阅读