转换SPSS和R之间的小时数

时间:2013-10-04 14:49:43

标签: r lubridate

我在SPSS中构建了每小时数据。使用Starttime 7:00和EndTime 7:59。当我在R中读到这些时,我得到了这样的数字:57600& 61140.如何让R将这些值识别为小时数?感谢您的帮助* 强文 *

1 个答案:

答案 0 :(得分:1)

我猜您在R中获得的这些数字是以秒为单位的相应小时数,例如02:51:03 = 2 * 60 * 60 + 51 * 60 + 3 = 10263秒。不符合我猜测的是7:00不是57600秒,但要么是25200秒(am),要么是68400秒(pm)。 57600秒对应16:00(下午4:00)。

如果这些值实际上是秒,那么您可以使用以下函数toHour将它们转换为时间。

    toHour <- function(x, seconds = F)  # x is a value of seconds
    {
     hours <- x %/% 3600
     secs. <- x %% 3600
     mins <- secs. %/% 60
     secs <- secs. %% 60

     ## add a 0 to single-digit hours / minutes / seconds to make it look nicer  
     mytime <- c(hours, mins, secs)
     for(i in 1:length(mytime))  
      {
       if(length(unlist(strsplit(as.character(mytime[i]), split = ""))) == 1)
        {
         mytime[i] <- paste(0, mytime[i], sep = "", collapse = "")
        }
      }
     ##

    if(seconds == T)
      {
       return(paste(mytime[1], mytime[2], mytime[3], sep = ":", collapse = ""))
      }
     if(seconds == F)
      {
       return(paste(mytime[1], mytime[2], sep = ":", collapse = ""))
      }
    }

    toHour(10263, seconds = T) # check function
    #[1] "02:51:03" #checked
    my_seconds <- seq(57600,61140, 60) # I guess you have no seconds in your time and, so, "my_seconds" is the values you get in R
    sapply(my_seconds, toHour) # turn all values (seconds) to hours:minutes
    #[1] "16:00" "16:01" "16:02" "16:03" "16:04" ...
    sapply(my_seconds, toHour, seconds = T) # turn all values (seconds) to hours:minutes:seconds
    #[1] "16:00:00" "16:01:00" "16:02:00" "16:03:00" ...

如果我误解了这个问题或者我的帖子无关紧要,我很抱歉,但由于声誉不佳,我无法在评论中询问详细信息。

编辑:toHour返回字符值。下一步是:

    library(chron)
    chron(times. = sapply(my_seconds, toHour, seconds = T))
    #[1] 16:00:00 16:01:00 16:02:00 16:03:00 16:04:00 ...