[英]R - converting dates within data.frame
I am working with a " data.frame
" which are given in the following formate: Aug 12, 2017. 我正在使用以下
data.frame
提供的“ data.frame
”:2017年8月12日。
class(data[,1]) = factor
How can i convert these into dates? 如何将它们转换为日期?
data[,1] <- as.Date.factor(data[,1],format = "%m.%d.%y")
, returns NA
's. data[,1] <- as.Date.factor(data[,1],format = "%m.%d.%y")
,返回NA
。
I would suggest the package lubridate
for very easy to use functions to operate with dates. 我建议使用
lubridate
软件包,因为它非常易于使用,可以与日期一起使用。 For example: 例如:
mdy("Aug 12,2017")
[1] "2017-08-12"
If your date is in YYYY-MM-DD format, you can use the ymd
function. 如果日期为YYYY-MM-DD格式,则可以使用
ymd
函数。 There are also other functions such as dmy
, dmy_hms
(for datetime), etc. 还有其他功能,例如
dmy
, dmy_hms
(用于日期时间)等。
If your column is called my.date
, you can do: 如果您的列名为
my.date
,则可以执行以下操作:
data$my.date <- mdy(data$my.date)
Alternatively, you can use the %<>%
operator from magrittr
to make your code even shorter: 另外,您可以使用
magrittr
的%<>%
运算符来使代码更短:
data$my.date %<>% mdy
Use as.POSIXct
(Base-R Solution): as.POSIXct
(Base-R解决方案):
as.POSIXct("Aug 12,2017", format="%b%d,%Y")
Output: 输出:
[1] "2017-08-12 CEST"
Using strptime
, could work: 使用
strptime
,可以工作:
strptime("Aug 12,2017", "%b%d,%Y")
Output: 输出:
[1] "2017-08-12 UTC"
The second parameter for strptime
is the format of the dates you have. strptime
的第二个参数是日期的格式。 For instance, if your dates are like this "1/5/2005"
, then the format would be: 例如,如果您的日期类似于
"1/5/2005"
,则格式为:
format="%m/%d/%Y"
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.