将秒转换为持续时间

时间:2013-02-08 01:37:14

标签: r lubridate

我刚开始用R.

我的数据位于csv文件中。这是一段摘录:

p,   t,  a,           b,           c
p01, t1, 4292.226015, 4292.226015, 0.0
p01, t3, 693.795607,  693.795607,  0.0
p02, t1, 262.798468,  262.798468,  0.0
p02, t2, 113.381499,  113.381499,  0.0
p02, t3, 325.854107,  325.854107,  0.0
p02, t4, 428.073246,  428.073246,  0.0
p02, t5, 319.010848,  319.010848,  0.0

......我正在加载它:

data <- read.csv(file='data.csv',head=TRUE,sep=',')

最后三列是持续时间值(以秒为单位),我希望它们是lubridate的duration个对象。我怎样才能做到这一点?

我在加载csv后尝试转换列,如下所示:

data$a <- dseconds(data$a)
data$b <- dseconds(data$b)
data$c <- dseconds(data$c)

......起初它似乎有效。除了,当我要求摘要时,有几个警告,我在解释时遇到了一些麻烦:

> summary(tasks)
group  task  a               b               c
p01:2  t1:2  Min.   : 113.4  Min.   : 113.4  Min.   :0  
p01:5  t2:1  1st Qu.: 290.9  1st Qu.: 290.9  1st Qu.:0  
       t3:2  Median : 325.9  Median : 325.9  Median :0  
       t4:1  Mean   : 919.3  Mean   : 919.3  Mean   :0  
       t5:1  3rd Qu.: 560.9  3rd Qu.: 560.9  3rd Qu.:0  
             Max.   :4292.2  Max.   :4292.2  Max.   :0  
Warning messages:
1: In quantile.default(object) :
  Class 'Duration' has no 'names' slot; assigning a names attribute will create an invalid object
2: In summary.default(X[[3L]], ...) :
  Class 'Duration' has no 'names' slot; assigning a names attribute will create an invalid object
3: In summary.default(X[[3L]], ...) :
  Setting class(x) to multiple strings ("summaryDefault", "table", ...); result will no longer be an S4 object
> 

1 个答案:

答案 0 :(得分:2)

这是一个警告。 summary尝试将持续时间对象转换为类c("summaryDefault", "table") 您可以像这样重现:

   class(data$a) <- c("summaryDefault", "table")
Warning message:
In class(dat$da) <- c("summaryDefault", "table") :
  Setting class(x) to multiple strings ("summaryDefault", "table", ...); 
          result will no longer be an S4 object.

例如,您可以定义如何将Duration类强制转换为table类。

    setAs("Duration", "table", function(from) from@.Data) ## dummy coercion here

现在我可以在没有警告的情况下应用摘要

 summary(dat)
      p                  t                   a                b                c           da      
 Length:7           Length:7           Min.   : 113.4   Min.   : 113.4   Min.   :0   n.vars :0     
 Class :character   Class :character   1st Qu.: 290.9   1st Qu.: 290.9   1st Qu.:0   n.cases:6435  
 Mode  :character   Mode  :character   Median : 325.9   Median : 325.9   Median :0                 
                                       Mean   : 919.3   Mean   : 919.3   Mean   :0                 
                                       3rd Qu.: 560.9   3rd Qu.: 560.9   3rd Qu.:0                 
                                       Max.   :4292.2   Max.   :4292.2   Max.   :0