首页 > 解决方案 > 如何在 r 中指定日期格式?

问题描述

我在指定数据的日期格式时遇到问题,安排为:

Date    Longitude   Latitude    Elevation   Max Temperature Min Temperature Precipitation   Wind    Relative Humidity   Solar
1/1/1979    40.625  10.1473999  594 31.784  14.711  0   1.34012963  0.332977248 23.69273112
1/2/1979    40.625  10.1473999  594 30.548  15.001  0   1.440527678 0.445704584 23.2192062
1/3/1979    40.625  10.1473999  594 30.029  18.724  0.020599366 1.950813349 0.532062642 18.34447248
1/4/1979    40.625  10.1473999  594 31.311  17.802  0   2.150911946 0.466495869 23.07077748

我尝试使用 as.Date 但结果如下:

gewane_t$Date <- as.Date(gewane_t$Date,format("%m/%d/%Y"))

charToDate(x) 中的错误:字符串不是标准的明确格式

任何解决方案。

亲切的问候,

标签: r

解决方案


使用lubridate dmy功能。此函数自动返回 POSIXct 类的对象,并且可以使用因子或字符。

假设您的数据框被称为代码gewane_t 更新dmymdy

library(lubridate)
gewane_t$Date <- mdy(gewane_t$Date)

输出:

  Date       Longitude Latitude Elevation   Max Temperature    Min Temperature_1 Precipitation  Wind
  <date>         <dbl>    <dbl>     <dbl> <dbl>       <dbl>  <dbl>         <dbl>         <dbl> <dbl>
1 1979-01-01      40.6     10.1       594  31.8        14.7 0               1.34         0.333  23.7
2 1979-02-01      40.6     10.1       594  30.5        15.0 0               1.44         0.446  23.2
3 1979-03-01      40.6     10.1       594  30.0        18.7 0.0206          1.95         0.532  18.3
4 1979-04-01      40.6     10.1       594  31.3        17.8 0               2.15         0.466  23.1

推荐阅读