我有这个数据框
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
我正在尝试将 Time_.EST。字段转换为时间格式,但是当我运行时
x[,"Time_.EST."]<-format(as.Date(x[,"Time_.EST."], format="%H%M" ), format = "%H:%M")
此命令显示N / A,其中 Time_.EST。字段中有3个字符,但适用于4个字符。有没有解决方法。
答案 0 :(得分:2)
这将粘贴&#34; 0&#34;如果列中只有3个字符。
x[["Time_.EST."]] = ifelse(nchar(x[["Time_.EST."]]) == 3,
paste0("0", x[["Time_.EST."]]),
x[["Time_.EST."]])
答案 1 :(得分:1)
您可以使用sprintf函数填充到一定数量的数字,如下所示:
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)
然后,您将始终拥有一个4位数字来使用