0

我正在尝试将数据框中当前为字符的几个变量更改为时间。我只使用从 csv 文件中导入了我想要的变量

ids_dates_times <- read.csv("filename", header=TRUE, na.strings=c(".",NA),
                            stringsAsFactor = FALSE, 
                            colClasses="character")[,c(1,3,8,9,10,15,16,17,22,23,24,29,30,31,36,37,38,43,44,45,50,51)]

ids_dates_times 示例(这只是前 4 个变量,注意有 14 个需要转换为时间):

       id_phresh   D1_Date    D1_Bed_Time  D1_Wake_Time
  1      1097      9/3/2016    15:16:00      8:59:00
  2      1098      7/22/2016    2:00:00      6:30:00
  3      2005      8/25/2016   23:00:00      6:00:00
  4      2007      7/9/2016     1:00:00      7:00:00
  5      2013      6/23/2016   23:45:00      8:35:00

我希望我的下一行代码将选定的列转换为时间。

times <- chron(times.= ids_dates_times[,c(3,4,6,7,9,10,12,13,15,16,18,19,21,22)], format = "hh:mm:ss")

我收到以下错误

convert.times(times., fmt) 中的错误:格式 hh:mm:ss 可能不正确

我尝试了以下方法:

itimes <- which(sapply(DF, function(x) all(grepl(":.*:", x))))
DF[itimes] <- lapply(DF[itimes], times)
idates <- which(sapply(DF, function(x) all(grepl("/.*/", x))))
DF[idates] <- lapply(DF[idates], dates)

这导致:

str(lapply(DF, class))

List of 22 $ id_phresh : chr "character" $ D1_Date : chr "character" $ D1_Bed_Time : chr "character" $ D1_Wake_Time: chr "character"

这些应该是日期和时间,而不是字符,对吗?任何帮助都是极好的!

4

1 回答 1

0

假设这DF在最后的注释中可重现,那么如果我们提前知道时间和日期列的索引,即itimes已知idates以下,那么它将是:

library(chron)

itimes <- 3:4
DF[itimes] <- lapply(DF[itimes], times)
idates <- 2
DF[idates] <- lapply(DF[idates], dates)

给予:

> str(lapply(DF, class))
List of 4
 $ id_phresh   : chr "integer"
 $ D1_Date     : chr [1:2] "dates" "times"
 $ D1_Bed_Time : chr "times"
 $ D1_Wake_Time: chr "times"

或者我们可以分别计算itimesidates作为具有两个 : 和两个 / 的列,然后运行上面的代码。lapply陈述。

itimes <- which(sapply(DF, function(x) all(grepl(":.*:", x))))
DF[itimes] <- lapply(DF[itimes], times)

idates <- which(sapply(DF, function(x) all(grepl("/.*/", x))))
DF[idates] <- lapply(DF[idates], dates)

或者,我们可以像这样使用一个 lapply:

DF[] <- lapply(DF, function(x) {
  if (all(grepl(":.*:", x))) x <- times(x)
  if (all(grepl("/.*/", x))) x <- dates(x)
  x
})

笔记

Lines <- "
       id_phresh   D1_Date    D1_Bed_Time  D1_Wake_Time
  1      1097      9/3/2016    15:16:00      8:59:00
  2      1098      7/22/2016    2:00:00      6:30:00
  3      2005      8/25/2016   23:00:00      6:00:00
  4      2007      7/9/2016     1:00:00      7:00:00
  5      2013      6/23/2016   23:45:00      8:35:00"
DF <- read.table(text = Lines, as.is = TRUE)
于 2018-03-30T21:18:36.783 回答