R ifelse避免更改日期格式 [英] R ifelse avoiding change in date format

查看:125
本文介绍了R ifelse避免更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ifesle两个日期。我有两列 - DateIn和DateOut。我需要添加第3个变量,如果有日期值,则显示DateOut,如果存在,则显示DateIn:

I am trying to make ifesle for two dates. I have two columns- DateIn and DateOut. I need to add 3rd variable, which would show "DateOut" if there is date value, or DateIn if there is :

DateIn     DateOut     Travel date
2010-11-24 <NA>        2010-11-24
2011-12-21 2012-01-21  2012-01-21
2010-10-25 2010-11-25  2010-11-25
2014-01-14 <NA>        2014-01-14

我试图用

TravelDate <- ifelse(is.na(DateIn), DateOut, DateIn)

但我得到的结果是:

    DateIn     DateOut     Travel date
2010-11-24 <NA>            15018
2011-12-21 2012-01-21      15151
2010-10-25 2010-11-25      14972
2014-01-14 <NA>            14972

旅行日期被归类为逻辑
有没有办法如何实现rusult withou R转换日期到数字?

Travel date is classified as "logical" Is there a ways how to achieve the rusult withou R transforming date to number?

非常感谢!

推荐答案

p>如果 dat 是数据集。我认为是 is.na(DateOut)旅行日期

If dat is the dataset. I assume it is is.na(DateOut) from the Travel date column

 as.Date(with(dat, ifelse(is.na(DateOut), DateIn, DateOut)),origin="1970-01-01")
#[1] "2010-11-24" "2012-01-21" "2010-11-25" "2014-01-14"

或者你可以做:

 dat$Travel.date <- dat$DateOut
 dat$Travel.date[is.na(dat$Travel.date)] <- dat$DateIn[is.na(dat$Travel.date)]
  dat
 #      DateIn    DateOut Travel.date
 #1 2010-11-24       <NA>  2010-11-24
 #2 2011-12-21 2012-01-21  2012-01-21
 #3 2010-10-25 2010-11-25  2010-11-25
 #4 2014-01-14       <NA>  2014-01-14

这篇关于R ifelse避免更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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