从R中的strptime()字符串中提取时间,返回NA [英] Extracting time from character string with strptime() in R, returning NA

查看:1744
本文介绍了从R中的strptime()字符串中提取时间,返回NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从R中的字符串中提取出时间,因此不能停止获取NA。我已经尝试了许多变体的正则表达式标签,但似乎无法解决这个简单的问题。任何帮助/澄清表示赞赏。



以下是我的代码示例:

 > x 
[1]2/7/2013 7:43
> class(x)
[1]character
> z > z
[1] NA


解决方案

不知道你的字符串是一个datetime。所以做一个第一:

  y<  -  strptime(x,format ='%m /%d /%Y% H:%M')

如果你试图只得到日期,你可以这样做: / p>

  strptime(x,'%m /%d /%Y')
/ pre>

因为 strptime 丢弃任何超出您的格式字符串的额外字符,但您不能抓住尾随%H:%M 因为该函数不知道从哪里开始。



一旦它是一个正确的datetime类,你可以做的事情:

  strftime(y,'%H:%M')

我更喜欢使用 as.POSIXlt 而不是 strptime 格式而不是 strftime ...但它们大致相当。 >

I am trying to extract out the time from a character string in R and can't stop getting NA as a result. I have tried numerous variations of the regular expression tags, but can't seem to get around this simple problem. Any help/clarifications are appreciated.

Here is my code for an example:

> x
[1] "2/7/2013 7:43"
> class(x)
[1] "character"
> z <- strptime(x, "%H:%M")
> z
[1] NA

解决方案

R doesn't know that your string is a datetime. So make it one first:

y <- strptime(x, format='%m/%d/%Y %H:%M')

If you were trying to get just the date, you could do:

strptime(x, '%m/%d/%Y') 

Because strptime discards any extra characters past your format string, but you cannot grab the trailing %H:%M because the function doesn't know where to start.

Once it is a proper datetime class, you can do things to it:

strftime(y, '%H:%M')

I prefer to use as.POSIXlt rather than strptime and format instead of strftime... but they are roughly equivalent.

这篇关于从R中的strptime()字符串中提取时间,返回NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆