R if语句跨数据表的列填充新列

时间:2014-11-04 17:07:41

标签: r

data <- data.frame(dates = c("2014-10-28 00:01:59.526","2014-10-27 13:30:01.526"),
                   times = c("23:59:59","13:29:55"),
                   hour = c(23,13),
                   minute = c(59,29),
                   second = c(59,55))
data[,1] <- as.POSIXct(data[,1])
data[,2] <- as.factor(data[,2])
class(data[,1])
class(data[,2])
class(data[,3])
class(data[,4])
class(data[,5])
      data

                    dates    times hour minute second
1 2014-10-28 00:01:59.526 23:59:59   23     59     59
2 2014-10-27 13:30:01.526 13:29:55   13     29     55

我需要使用POSIXct数据填充新列“NewDate”,该数据是日期和时间列的组合但是如果小时栏显示23那么“NEwDate”的日期应该是“日期”的日期“列减1天,否则应该是”日期“列的日期。

所以最终的输出应该是:

             date           time     hour   minute second  NewDate      
1 2014-10-28 00:01:59.526   23:59:59   23    59     59  2014-10-27 23:59:59 #NewDate =  date-1 + time
2 2014-10-27 13:30:01.526   13:29:55   13     29      55  2014-10-17 13:29:55 #NewDate = date + time

(NewDate必须是POSIXct)

在没有循环数据框并执行以下操作的情况下,执行此操作的最佳方法是什么:

library(lubridate) #lubridate contains hour(), minute(), second()

CorrectTIME <- function(date, hour, minute, second)
{
  NewDate<- vector("numeric",length(date))
  for(i in 1:length(date))
  {
        if(hour[i] > hour(date[i]) ) 
        {
          NewDate[i] =ISOdatetime(year(date[i]), month(date[i]), day(date[i])-1, hour[i], minute[i], second[i], tz="GMT")
        }else
        {
          NewDate[i] =ISOdatetime(year(date[i]), month(date[i]), day(date[i]), hour[i], minute[i], second[i], tz="GMT")
        }
  }

}

1 个答案:

答案 0 :(得分:0)

with(data, paste ( format( as.Date(dates) - (hour == 23) , "%Y-%m-%d"), 
           paste( hour, minute, second, sep=":")))
#[1] "2014-10-27 23:59:59" "2014-10-27 13:29:55"

哎呀,忘了as.POSIXct:

as.POSIXct( with(data, paste ( format( as.Date(dates) - (hour==23) , 
            "%Y-%m-%d"),  paste( hour, minute, second, sep=":"))) )
[1] "2014-10-27 23:59:59 PDT" "2014-10-27 13:29:55 PDT"