R-日期时间变量在ifelse之后丢失格式 [英] R- date time variable loses format after ifelse

查看:89
本文介绍了R-日期时间变量在ifelse之后丢失格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正确的POSIXct格式的变量,已用ymd_hms(DateTime){lubridate}转换. 但是,转换后,变量将失去其POSIXct格式:

I have a variable in the proper POSIXct format, converted with ymd_hms(DateTime) {lubridate}. However, after a transformation the variable loses its POSIXct format:

daily$DateTime<- ifelse(daily$ID %in% "r1_1"|daily$ID %in% "r1_2", 
                   NA,daily$DateTime)

我尝试使用lubridate将变量再次转换为POSIXct,但似乎不像NA,此外,变量DateTime现在具有lubridate不能识别为日期和时间的num格式.格式(例如1377419400).

I try to convert the variable again to POSIXct with lubridate, but it seems it does´t like the NAs, and, in addition, now the variable DateTime has a num format that lubridate does´t recognise as a date and time format (e.g. 1377419400).

请帮助我们进行必要的转换,以在ID == r1_1和r1_2时将DateTime转换为NA ??

Please, any help to make the required transformation to convert to NA the DateTime when ID== r1_1 and r1_2??

谢谢

推荐答案

以下方法应该起作用:

daily <- data.frame(DateTime = seq(Sys.time(), length.out=10, by=1000), ID=rep(1:2,5))
daily$DateTime[daily$ID%in%2]<-NA

(尽管使用is.na<-的解决方案也很好.设置is.na的一般逻辑没有多大意义-但这没问题,只要您确保事情不会变得太复杂了.)

(Although the solution with is.na<- is fine too. There is just the general logic of setting is.na that doesn't make much sense - but that's no problem as long as you make sure things don't get too complicated.)

ifelse进行了一些隐式转换,所以我认为不可能使用ifelse保存日期类.

ifelse does some implicit conversions so I don't think it would ever be possible to have a date class preserved using ifelse.

这篇关于R-日期时间变量在ifelse之后丢失格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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