【发布时间】:2018-03-30 18:51:39
【问题描述】:
我正在尝试将数据框中当前为字符的几个变量更改为时间。 我只使用了从 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"
这些应该是日期和时间,而不是字符,对吧? 任何帮助都会很棒!
【问题讨论】:
-
请分享
ids_dates_times的部分内容,以便我们了解问题。你可以分享head(ids_dates_times, 5)。 -
尝试使用
format = "h:m:s"(或不使用该格式,在?chron底部的示例中,它们显示它默认使用这种格式。) -
format = "h:m:s" 返回相同的错误,但针对不同的输入代码进行了调整(hh:mm:ss --> h:m:s)。忽略它会返回相同的结果