Reputation: 130
Hi i have this data frame
Table_Number.130. ID_HOUR Date Time_.EST. 1 137 480 365 600 2 340 0 365 1612 3 340 0 365 1619 4 340 0 365 657 5 340 0 365 700 6 129 60 365 700 7 340 0 365 1703 8 340 0 365 1709 9 340 0 365 1740 10 340 0 365 1755 11 129 60 365 800 12 340 0 365 804 13 340 0 365 811 14 340 0 365 1817 15 340 0 365 1825 16 340 0 365 1833 17 340 0 365 1839 18 340 0 365 1848 19 340 0 365 1857 20 129 60 365 1900
I am trying to convert Time_.EST. field into time format but when i run
x[,"Time_.EST."]<-format(as.Date(x[,"Time_.EST."], format="%H%M" ), format = "%H:%M")
This command shows N/A where there are 3 characters in Time_.EST. field but works fine for 4 characters. Is there a workaround for this.
Upvotes: 1
Views: 243
Reputation: 1219
You could pad out to a set number of digits using the sprintf function as below:
newtime <- sprintf("%04d",times$time)
#Make a new list with at least 4 digits: adds leading zeroes as needed
times <- cbind(newtime,times)
#Combine the two together
#A single step would also work
times$newtimes <- sprintf("%04d",times$time)
Then you will always have a 4 digit number to work with
Upvotes: 1
Reputation: 145765
This will paste a "0" on if there are just 3 characters in the column.
x[["Time_.EST."]] = ifelse(nchar(x[["Time_.EST."]]) == 3,
paste0("0", x[["Time_.EST."]]),
x[["Time_.EST."]])
Upvotes: 2