【问题标题】:Removing rows of data in R below a specified value删除 R 中低于指定值的数据行
【发布时间】:2015-06-30 23:10:43
【问题描述】:

我想知道是否有人可以帮忙...

我有一个包含连续时间列的数据框,我正在尝试删除指定时间以下的所有行。

数据从大约开始。 11:29:00 但我想在 12:30.00 之前和 14:20.00 之后删除所有行。 由于每秒都会记录数据,因此删除不必要的行将是一个很大的帮助,并且使管理这些数据对我来说更容易,因此非常感谢任何帮助。

这是数据帧的头部,可以看到时间是连续的,以秒为单位。我想删除 GPS.Time 列中截至 12:30:00 的所有这些行。希望这是有道理的。

        Raw.Vel.        Smooth.Vel.        GPS.Time

        1.486               0.755         11:39:39
        1.425               1.167         11:39:40
        1.466               1.398         11:39:41
        1.533               1.552         11:39:42
        1.517               1.594         11:39:43
        1.918               1.556         11:39:44

创建上述数据框:

Raw.Vel. <- c(1.486,1.425, 1.466, 1.533, 1.517, 1.918)
Smooth.Vel. <- c(0.755, 1.167, 1.398, 1.552, 1.594, 1.556)
GPS.Time <- c("11:39:39", "11:39:40", "11:39:41", "11:39:42", "11:39:43", "11:39:44")
sample <- data.frame(Raw.Vel., Smooth.Vel., GPS.Time)

提前致谢。

【问题讨论】:

  • 请添加一些示例数据,以便我们更好地了解您的需求,使问题更具重现性。
  • 你可以从简单的例子开始,比如DF &lt;- data.frame(x = 1:5); DF[ DF$x &gt; 2 &amp; DF$x &lt; 5 ,]subset命令
  • “可重现”意味着数据可以从您的答案(而不是评论)复制粘贴到 R 中,以便我们查看与您相同的数据。有用的参考:stackoverflow.com/a/28481250/1191259
  • 您可以通过 df[df$date > as.Date("2015-04-01"),] 进行过滤
  • 我现在在问题中包含了一个数据示例。

标签: r delete-row threshold


【解决方案1】:

使用lubridate 包将您的字符串时间列转换为某种时间类:

library(lubridate) 
sample$GPS.Time <- hms(sample$GPS.Time)

要获得所需的输出,只需使用带括号的子集 ([),并满足您想要的条件。在您的示例中,我删除了 11:39:42 之前的所有行。

output <- sample[sample$GPS.Time < hms("11:39:42"),]

【讨论】:

  • 谢谢,这对我的数据集有效。虽然我必须使用 >= 而不是
【解决方案2】:

将 GPS.Time 转换为“POSIXct”对象:

df$time <- as.POSIXct(df$GPS.Time, format="%H:%M:%S")

然后你可以使用逻辑过滤:

filtered_df <- df[df$time < as.POSIXct("12:30:00", format="%H:%M:%S"), ]

【讨论】:

    【解决方案3】:

    您可以将“GPS.Time”列中的条目转换为字符(这原本是一个因子变量)。之后,您可以通过将时间与指定的截止时间进行比较来分离集合,该截止时间存储为应以相同格式 (HH:MM:SS) 写入的字符串:

    sample$GPS.Time <- as.character(sample$GPS.Time)
    cutoff_time <- "11:39:42" # modify as necessary
    sample <- sample[-which(sample$GPS.Time < cutoff_time),] #remove all rows with times smaller than the cutoff_time
    #> sample
    #    Raw.Vel. Smooth.Vel. GPS.Time
    #4    1.533       1.552 11:39:42
    #5    1.517       1.594 11:39:43
    #6    1.918       1.556 11:39:44
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多