简体   繁体   中英

Deleting the last 3 characters in a specific column in every row

I have the following code. I would like to delete every last 3 characters from each row in the column REAL_TIME_ARR, so that there are no seconds displayed.

Additionally, I would like to add a 0 in front of every value that begins with a single value (1, 2, 3, 4, 5, 6, 7, 8, 9).

    TwentyFourSeptTrainData
    REAL_TIME_ARR        
 1        8:38:01                
 2        8:40:02                
 3        8:45:22                
 4        9:00:59                
 5        9:07:21                
 6        11:10:11        
 and so on and so on        

My desired data:

  TwentyFourSeptTrainData
     REAL_TIME_ARR        
  1        08:38                
  2        08:40                
  3        08:45                
  4        09:00                
  5        09:07                
  6        11:10        
  and so on and so on   

I think your best option is to recognise that you are working with times, and to use the R functions for dates and times to read the string you have as a datetime and write it back in the format you want.

So try:

REAL_TIME_ARR_2 <- as.character( 
   as.POSIXlt(REAL_TIME_ARR, format="%H:%M:%S"), 
   format="%H:%M"
   )
stringr::str_pad(
    substring(mydata$REAL_TIME_ARR,1,nchar(mydata$REAL_TIME_ARR)-3), 
    width=5, side = "left", pad = "0")
[1] "08:38" "08:40" "08:45" "09:00" "09:07" "11:10"

Using substring, you can save only the characters from 1 up to the total ( nchar ) minus three. Wrap this with stringr 's str_pad to add zeros where needed. You can assign this back into mydata$REAL_TIME_ARR .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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