将R中的时间转换为24小时

时间:2017-10-19 21:04:20

标签: r

为简单起见,我创建了以下代码:

  some_data <- c(1, 12, 500, 1800, 9, 1230)
  df <- as.data.frame(some_data)

我想将这些时间转换为24小时。例如,最终输出应为(1300,1200,1700,1800,900,1230)

我遇到的主要问题是,有些数据没有尾随0或00,与1PM一样,但其他数据则如此。我不确定如何将其添加到仅缺少它的时间。这些时间是课堂时间,所以12-7是PM,而8-11是AM。有没有更有效的方法来做到这一点,还是我必须手动更改它,因为时间变化?

2 个答案:

答案 0 :(得分:1)

这适用于您的样本集

df$some_data=ifelse(df$some_data>100,df$some_data/100,df$some_data)
df$some_data=ifelse((df$some_data>=8&df$some_data<=11)|df$some_data>=12,df$some_data,df$some_data+12)

df$some_data*100
[1] 1300 1200 1700 1800  900 1230

答案 1 :(得分:1)

应该可以安全地假设所有小于100的时间都需要乘以100.之后,只需要在800之前纠正时间:


correct_times <- function(times) {
  times_hmm <- ifelse(times < 100,
                      times * 100,
                      times)

  ifelse(times_hmm < 800,
         times_hmm + 1200,
         times_hmm)
}
correct_times(c(1, 12, 500, 1800, 9, 1230))
#> [1] 1300 1200 1700 1800  900 1230