简体   繁体   English

在R中从Excel中读入时间

[英]Read in times from Excel in R

I have data saved in Excel that includes time data. 我有保存在Excel中的数据,其中包括时间数据。

When reading it in with read.xlsx in R, it adds "1899-12-30" to the time column, I presume in an attempt to read in a date in addition to the time that doesn't exist. 使用R中的read.xlsx进行读取时,它会在时间列中添加“ 1899-12-30”,我想尝试除不存在的时间以外还读取日期。

library(xlsx)

times<-read.xlsx("times.xlsx", sheetName = "Sheet1")
times
             Time
1 1899-12-30 20:13:24
2 1899-12-30 08:13:54
3 1899-12-30 08:14:24
4 1899-12-30 08:14:54
5 1899-12-30 08:15:24

I tried 我试过了

times<-read.xlsx("times.xlsx", sheetName = "Sheet1", colClasses('POSIXct'))

and

times<-read.xlsx("times.xlsx", sheetName = "Sheet1", colClasses('POSIXct(format='%H:%M:%S')'))

but the first doesn't do anything and the second gives me an error. 但是第一个不执行任何操作,第二个给我一个错误。

Note that read.xlsx() recognizes TIME as %H:%M:%S , and converts it into the dummy POSIXct/POSIXt object, ie 1899-12-31 08:00:00 and 1899-12-31 20:00:00 请注意, read.xlsx()将TIME识别为%H:%M:%S ,并将其转换为虚拟POSIXct / POSIXt对象,即1899-12-31 08:00:00和1899-12-31 20:00 :00

#use readxl
library(readxl)
df <- read_excel('test.xlsx')

OR use format 或使用format

read.xlsx("myfile.xlsx") %>%
  mutate(
    TIME = format(TIME, "%I:%M %p")
    )

OR after reading df convert it into time using 或读取df后,使用以下命令将其转换为时间

as.POSIXct(df$Time, format="%H:%M:%S", tz="CET")

EDIT: I don't have data to replicate your errors or problem that you are facing , so i have made one according to those date format 编辑:我没有数据可以复制您遇到的错误或问题,所以我已根据那些日期格式制作了一个

df = data.frame(Time = c("1899-12-30 20:13:24","1899-12-30 08:13:54","1899-12-30 08:14:24","1899-12-30 08:14:54","1899-12-30 08:15:24"))

df <- as.POSIXct(df$Time, format = "%Y-%m-%d %H:%M") #apply  function to create a POSIXct object

#use the `strftime()` function to split the column and then the function times() to create a chronological object.
library(chron)
time <- times(strftime(df, format="%H:%M:%S"))

This method should def work, hope you got the idea there are many ways to achieve this 此方法应该有效,希望您有很多实现此目标的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM