失败通过使用as.date提取的时间戳的日期和if.else

问题描述:

我已读入作为MYDATA,现有列称为inbound_date csv文件,包含像失败通过使用as.date提取的时间戳的日期和if.else

NULL

数据

2017年6月24日16时47分35秒

2017年6月24日16时47分35秒

我想创建一个新列撷取日此列。我曾尝试下面的代码,但失败了,

mydata$inbound_day<-ifelse(is.null(mydata$inbound_date),"null",as.Date(mydata$inbound_date,format = "%Y-%m-%d"))

新列inbound_day已经加入,但它显示为NA在所有行的列。

可以帮忙看看代码,哪部分是错的?谢谢!

有两件事情在这里打球。

1. The behaviour of `ifelse`. It will return as many values as the 
lengtch of condition. If the condition returns only one value, it 
will only return one value. 

2. The behaviour of `is.null` is not the same is `is.na`. Unlike `is.na`, `is.null(mydata$inbound_date)` is checking the whole 
of `mydata$inbound_date1` as a single object and you are getting 
just one value in return, which is False 

这两件事的联合作用是,您只是将第一个项目的as.Date值作为结果,并且它是一个单独的'NA . This NA正在被回收以使用NA填充整个列。

解决方法 - 使用is.na您使用的是is.null。它会返回多个值,并且事情将按预期工作。

你必须指定时间。

x <- as.POSIXlt("2017-06-24 16:47:35", format = "%Y-%m-%d %H:%M:%S") 

format(x, "%Y-%m-%d") 
[1] "2017-06-24" 

使用lubridate,而不是格式化as.date的则在提取日

library(lubridate) 
x <- ymd_hms("2017-06-24 16:47:35") 
format(x, "%d")