简体   繁体   English

从R中的时间减去一个数字

[英]Subtracting a number from time in R

I have a data frame with two time columns containing times ranging from 0:00 - 23:59.我有一个数据框,其中包含两个时间列,时间范围为 0:00 - 23:59。 This data was supposed to be collected in a 0:00-12:00 format, but there was an error made in the Redcap survey allowing the respondents to choose in military times.该数据本应以 0:00-12:00 的格式收集,但 Redcap 调查中出现错误,允许受访者选择军事时期。

I need to subtract 12:00 from all values that are greater than 12:00 so that I get the range from military to standard, yet I cannot find an obvious way to go about this.我需要从所有大于 12:00 的值中减去 12:00,以便得到从军用到标准的范围,但我找不到明显的方法来解决这个问题。

Here is an approximation of the for loop I was trying - I just am unaware of how to subtract a number from hours in the column once I have transformed it with lubridate which is why I have not tried that.这是我正在尝试的 for 循环的近似值 - 我只是不知道如何在使用 lubridate 对其进行转换后从列中的小时数中减去一个数字,这就是我没有尝试过的原因。

Additionally, I tried difftime but am not sure how to use it when I am not subtracting two columns.此外,我尝试了 difftime,但不确定在不减去两列时如何使用它。

    if (is.na(df$var1)) {
    next
  }
    else if (x > "12:00") {
      x<-as.numeric(x)-12
    }
    print(x)
  }

Thanks谢谢

This quite simple approach requires conversion of your time data stored as characters to POSIXlt using strptime() , enabling to choose another format based on your individual specifications using format() :这种非常简单的方法需要使用strptime()将存储为字符的时间数据转换为 POSIXlt,从而可以使用format()根据您的个人规范选择另一种格式:

x <- c("04:12", "11:38", "15:39", "23:59")

strptime(x, format="%H:%M") |> format("%I:%M")
#> [1] "04:12" "11:38" "03:39" "11:59"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM