【问题标题】:How to specify the Date format in r?如何在 r 中指定日期格式?
【发布时间】:2021-07-14 07:12:39
【问题描述】:

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

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) 中的错误: 字符串不是标准的明确格式

任何解决方案。

亲切的问候,

【问题讨论】:

  • 代替as.Date(gewane_t$Date, format("%m/%d/%Y")试试as.Date(gewane_t$Date, format = "%m/%d/%Y")
  • 这是结果。任何建议.gewane_t$Date
  • 这是一条奇怪的信息。这表明gewane_t$Date 是数字。从上表和您的错误消息中,我建议它是一个字符串。此文件是否在 Excel 中打开并保存? Excel 显示日期,但在后台它只是一个数字。
  • 是的,它保存在 excel 中。
  • 啊,好吧,如果该列是日期格式,并且您将其保存为 csv 文件,那么它将被保存为数字(即 Windows 上截至 01-01-1900 的天数机器和 Mac 机器上的 01-01-1904)。你可以试试:as.Date(gewane_t$Date, origin = "1900-01-01")

标签: r


【解决方案1】:

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

假设您的数据框名为gewane_t 代码dmy更新为mdy

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

【讨论】:

  • 这个结果来了:gewane_t$Date
  • 好的,我会检查
  • 我已经检查过了。你有没有安装lubridateinstall.packages("lubridate")?是您的数据框的名称gewane_t 那么它应该可以工作。请告诉我。
  • 结果是一样的。 > setwd("C:/Users/c/OneDrive/Desktop/Hydroclimatology/CFSR 水文气候学数据/Gewane") > gewanet 类(gewanet) [1] "data.frame" > library(lubridate) 附加包:'lubridate' 以下对象从 'package:base' 中屏蔽:date、intersect、setdiff、union > gewanet$Date
  • 是不是因为我的数据格式是mm/dd/yyyy?
猜你喜欢
  • 2016-03-08
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2015-03-12
相关资源
最近更新 更多