Search code examples
rdatetimedataframedate-format

Change all date format in dataframe


I am very new to R programming and kind of stuck in this: I have a dataframe and I want check if there any value in any of the rows/columns which is in date format, should be stripped off to only time part. For example a date string of "2015-01-02 10:15:44" should be changed to "10:15:44"

I know, it's very novice approach, but here is what I am trying to take substring of all values.

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)

Can someone please suggest a way out?


Solution

  • Loop through columns and substring:

    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"))