简体   繁体   English

用R进行数据和时间转换

[英]Data and time conversion with R

I'm using R Studio. 我正在使用R Studio。 When I try to convert the date and time format using as.Date or as.Time I'm getting NA as the result. 当我尝试使用as.Date或as.Time转换日期和时间格式时,得到的结果是NA。 I also tried to set the Locale as it has been recommended in some of the problems in SO, that's also not helping. 我还尝试设置语言环境,因为在SO中的某些问题中建议这样做,这也无济于事。 The default class is factor after I import from the text file. 从文本文件导入后,默认类为factor。 I also tried to make it a character. 我也试图使它成为一个角色。 Still the problem exists. 问题仍然存在。 Any help? 有什么帮助吗?

> x<-c("16-12-2006")  
> class(x)
[1] "character"
> y<-as.Date(x)
> class(y)
[1] "Date"
> y<-as.Date(x,format="d%m%Y%")
> class(y)
[1] "Date"
> y
[1] NA

You are just misplacing the % s and missing the - s in your format string. 您只是在格式字符串中放错了% s而缺少- The format string needs to match the string characters exactly (spaces, hyphens, commas, colons, etc.). 格式字符串需要与字符串字符完全匹配(空格,连字符,逗号,冒号等)。 See the document: Date-time Conversion Functions to and from Character . 请参阅文档: 与字符之间的日期时间转换函数

Try: 尝试:

> y <- as.Date(x, format="%d-%m-%Y") 

and it should work. 它应该工作。

Try this: 尝试这个:

> x <- as.POSIXct(strptime("11-09-2015", "%d-%m-%Y"))
> as.Date(x)
[1] "2015-09-10"
> x
[1] "2015-09-11 CEST"

x is a class of "POSIXct" and "POSIXt", but as.Date(x) is a class of "Date" and you can use it as x-axis in ggplot. x是“ POSIXct”和“ POSIXt”的类,但是as.Date(x)是“ Date”的类,您可以将其用作ggplot中的x轴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM