1

我有一个名为 marathon 的数据集,我尝试使用 lubridate 和 churn 将 marathon$Official.Time 的字符转换为时间值,以便对其进行处理。我希望以分钟为单位显示时间(意味着 2 小时显示为 120 分钟)。

data.frame':    5616 obs. of  11 variables:
$ Overall.Position : int  1 2 3 4 5 6 7 8 9 10 ...
$ Gender.Position  : int  1 2 3 4 5 6 7 8 9 10 ...
$ Category.Position: int  1 1 2 2 3 4 3 4 5 5 ...
$ Category         : chr  "MMS" "MMI" "MMI" "MMS" ...
$ Race.No          : int  21080 14 2 21077 18 21 21078 21090 21084 12 ...
$ Country          : chr  "Kenya" "Kenya" "Ethiopia" "Kenya" ...
$ Official.Time    : chr  "2:12:12" "2:12:14" "2:12:20" "2:12:29" ...

我试过:

  library(lubridate)
  times(marathon$Official.Time) 

或者

  library(chron)
  chron(times=marathon$Official.Time)
  as.difftime(marathon$Official.Time, units = "mins")

但我只得到 NA

4

3 回答 3

1

你几乎在那里difftime(这需要两次并给你带来差异)。相反,使用as.difftime(这需要一个“差异” - 即马拉松时间)并将其指定format为小时:分钟:秒。

> as.difftime("2:12:12", format="%H:%M:%S", units="mins")
Time difference of 132.2 mins
> as.numeric(as.difftime("2:12:12", format="%H:%M:%S", units="mins"))
[1] 132.2

不需要额外的软件包。

于 2016-10-08T09:46:57.903 回答
0

感谢大家。我尝试了所有方法,所有方法都有效。我将 as.difftime 因为它对我来说看起来更容易

于 2016-10-08T11:07:00.263 回答
0

注意:@mathemetical.coffee 的解决方案是 ++gd 比这些更好。


手动将其踢出非常简单:

library(stringi)
library(purrr)

df <- data.frame(Official.Time=c("2:12:12","2:12:14","2:12:20","2:12:29"),
                 stringsAsFactors=FALSE)

map(df$Official.Time, function(x) {
  stri_split_fixed(x, ":")[[1]] %>%
    as.numeric() %>%
    `*`(c(60, 1, 1/60)) %>%
    sum()
}) -> df$minutes

df
##   Official.Time  minutes
## 1       2:12:12    132.2
## 2       2:12:14 132.2333
## 3       2:12:20 132.3333
## 4       2:12:29 132.4833

您也可以仅使用基本 R 操作和不使用“管道”来完成此操作:

df$minutes <- sapply(df$Official.Time, function(x) {

 x <- strsplit(x, ":", TRUE)[[1]]
 x <- as.numeric(x)
 x <- x * (c(60, 1, 1/60))

 sum(x)

}, USE.NAMES=FALSE)

如果“卡在”基础 R 上,那么我实际上会这样做:

vapply(df$Official.Time, function(x) {

 x <- strsplit(x, ":", TRUE)[[1]]
 x <- as.numeric(x)
 x <- x * (c(60, 1, 1/60))

 sum(x)

}, double(1), USE.NAMES=FALSE)

以确保类型安全。

但是,chron也可以使用:

library(chron)

60 * 24 * as.numeric(times(df$Official.Time))

注意lubridate没有times()功能。

于 2016-10-08T09:44:30.820 回答