r - 如何在 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 不适用
解决方案
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
推荐阅读
- python-3.x - 如果索引不匹配,Pandas 不会从系列中放置值
- kubernetes - 如何使用 OpenStack 在 Kubernetes 中的同一端口上公开多个服务
- firebase - Firestore ConnectionState 在颤振应用程序中永远处于等待状态
- c# - c# WinForms - 如何获取容器表单设置的UserControl的大小
- javascript - 为 D3 堆积条形图准备嵌套 JSON 数据
- c# - 系统异常:'无法创建没有列的表,它是否具有公共属性?
- c# - 如何通过C#中的集合存储和检索多维数据
- ios - 在 iOS 应用程序中使用 getstream.io 但文档还不够
- swift - 方法“应用程序:didRegisterUserNotificationSettings:”的重复声明
- android - 使用kotlin定义recyclerView时如何定义ViewHolder的构造函数