更改数据框中的所有日期格式

时间:2019-02-13 13:25:08

标签: r datetime dataframe date-format

我对R编程非常陌生,并且陷入了这种困境: 我有一个数据框,我想检查是否有任何行/列中的任何日期格式的值都应剥离为仅时间部分。 例如,日期字符串"2015-01-02 10:15:44"应该更改为"10:15:44"

我知道,这是一种非常新手的方法,但这是我尝试采用所有值的子字符串的方法。

id<-c(1,2,3,4)
time1<-c("2015-01-02 10:15:44","NA","2015-11-12 00:15:44","2015-01-02 12:15:14")
time2<-c("NA", "2015-01-02 10:15:44","NA","2015-11-12 00:15:44")
..
..
timen ....
print(df)

df<-data.frame(id,time1, time2,..., timen)
df[1:4 ,2: ncol(df)] <- substring(df[1:4 ,2: ncol(df)], 12)
print(df)

有人可以建议出路吗?

3 个答案:

答案 0 :(得分:2)

您是否尝试过软件包lubridate

time_cols <- c("time1", "time2")

df[time_cols] <- apply(df[time_cols], 2, 
                       function(col){
                          format(lubridate::ymd_hms(col), "%H:%M:%S")
                       })
df
#     id    time1    time2
#   1  1 10:15:44     <NA>
#   2  2     <NA> 10:15:44
#   3  3 00:15:44     <NA>
#   4  4 12:15:14 00:15:44

答案 1 :(得分:1)

尝试以下操作:df1包含您的数据。进行此操作后,您可以与原始数据重新组合。

    target<-unlist(sapply(stringr::str_extract_all(names(df1),"^t.*"),"["))
       Changed<-as.data.frame(sapply(target,function(x){ind=which(names(df1)==x)
       unlist(sapply(stringr::str_split(df1[,ind]," "),"[",2))}))
cbind(id=df1$id,Changed)

输出:

       id    time1    time2
       1    10:15:44     <NA>
       2     <NA>      10:15:44
       3   00:15:44       <NA>
       4    12:15:14 00:15:44

答案 2 :(得分:1)

循环浏览列和子字符串

df[, 2:3] <- lapply(df[, 2:3], substring, first = 12)
df
#   id    time1    time2
# 1  1 10:15:44         
# 2  2          10:15:44
# 3  3 00:15:44         
# 4  4 12:15:14 00:15:44  

# input data
df <- data.frame(id = c(1,2,3,4),
                 time1 = c("2015-01-02 10:15:44","NA","2015-11-12 00:15:44","2015-01-02 12:15:14"),
                 time2 = c("NA", "2015-01-02 10:15:44","NA","2015-11-12 00:15:44"))