我有三列用于日,月和年,我想用它来制作一个日期列
> dt
mon day year
1: NA NA NA
2: NA NA NA
3: NA NA NA
4: NA NA NA
5: NA NA NA
6: NA NA NA
7: NA NA NA
8: 10 10 2017
9: NA NA NA
10: 4 4 2018
11: NA NA NA
12: NA NA NA
13: NA NA NA
14: NA NA NA
15: NA NA NA
16: NA NA NA
>
我使用下面的代码,它给出了奇怪的结果:
> as.Date(paste(dt$mon,dt$day,dt$year,sep="-"),format = "%m-%d-%y")
[1] NA NA NA NA NA NA NA
[8] "2020-10-10" NA "2020-04-04" NA NA NA NA
[15] NA
我也在下面尝试过:
library("lubridate")
with(dt, ymd(sprintf('%04d%02d%02d', year, mon, day)))
这里我收到错误: sprintf出错("%04d%02d%02d",年,周一,日): 格式无效'%04d&#39 ;;使用格式%f,%e,%g或%a表示数字对象
请建议这些代码是否有任何问题,或者我的问题是否有更好的解决方案?
谢谢!
答案 0 :(得分:6)
您的年份是4位数格式。
所以你应该使用%Y
org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://maven.google.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom'.
at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:97)
Caused by: java.net.ConnectException: Operation timed out (Connection timed out)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:337)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134)
... 172 more
答案 1 :(得分:3)
这更像是@Giovana给出的答案的补充,但如果我们使用破折号将年份 - 月 - 日格式连接起来,我们甚至不需要将格式字符串传递给{{ 1}}:
as.Date
Check here使用上述逻辑进行简短演示。
答案 2 :(得分:3)
我们可以使用anytime
library(anytime)
anydate(do.call(paste, dt))
如果是data.table
dt[, date := anydate(do.call(paste, .SD))]