Om Sao
Om Sao

Reputation: 7643

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?

Upvotes: 1

Views: 126

Answers (3)

NelsonGon
NelsonGon

Reputation: 13309

Try this: df1 contains your data. You can recombine with original data after this manipulation.

    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)

Output:

       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

Upvotes: 1

zx8754
zx8754

Reputation: 56004

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

Upvotes: 1

DS_UNI
DS_UNI

Reputation: 2650

have you tried the package 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

Upvotes: 2

Related Questions