涉及日期的奇怪行为-“必须提供来源” [英] Strange behavior involving dates - "origin must be supplied"

查看:100
本文介绍了涉及日期的奇怪行为-“必须提供来源”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个数据表

dt <- data.table(x=as.Date(c("2014-1-1", "2015-1-1", "2016-1-1")), y=as.Date(c(NA, "2015-6-1", NA)))
dt
            x          y
1: 2014-01-01       <NA>
2: 2015-01-01 2015-06-01
3: 2016-01-01       <NA>

我想添加一列 z 等于y,其中y不是NA,否则等于x。

I want to add a column z which is equal to y where y is not NA, and x otherwise.

dt[, z:=ifelse(is.na(y), x, y)]
dt
            x          y     z
1: 2014-01-01       <NA> 16071
2: 2015-01-01 2015-06-01 16587
3: 2016-01-01       <NA> 16801

但是由于某种原因,以上语句将z强制转换为数字。如果我尝试将其转换为带有 as.Date 的日期,则会收到错误消息

But for some reason the above statement casts z to numeric. If I try to convert it to a date with as.Date I get an error

dt[, z:=as.Date(ifelse(is.na(y), x, y))]
Error in as.Date.numeric(ifelse(is.na(y), x, y)) : 'origin' must be supplied

给出的东西以及如何完成我的工作

What gives and how do I accomplish what I'm trying to do?

推荐答案


当R将日期视为整数时,其
的起源是1970年1月1日。

When R looks at dates as integers, its origin is January 1, 1970.

> https://stats.idre.ucla.edu/r/faq/how-does-r-handle-date-values/

dt[, z:=as.Date(ifelse(is.na(y), x, y), origin="1970-01-01")]

update:正如Frank所建议的那样,这似乎也可行,并且似乎不需要取消强制: dt [,z:= replace(y,is.na(y),x)] 。它会发出警告,请谨慎使用。

update: as Frank suggests, this also seems to work and does not seem to require un-coercion: dt[, z:=replace(y, is.na(y), x)]. It throws a warning so use w/ caution.

这篇关于涉及日期的奇怪行为-“必须提供来源”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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