r - 是否有将日期从整数转换为实际日期的 R 函数?
问题描述
我正在尝试执行以下命令来改变新列。如果 Lease.End.date 为空白,则应将其替换为 Distribution date 否则 Lease.End.Date。
我得到了正确日期列的不正确值
newdata <- data %>% select(FI, Lease.End.Date, Distribution.Date) %>% mutate(correctdate = ifelse(Lease.End.Date == "",
Distribution.Date,Lease.End.Date))
> typeof(newdata$correctdate)
[1] "integer"
> typeof(newdata$Lease.End.Date)
[1] "integer"
> typeof(newdata$Distribution.Date)
[1] "integer"
> data
FI Lease.End.Date Distribution.Date
1 3 31-Jul-25 13-Aug-19
2 3 13-Aug-19
3 3 13-Aug-19
4 3 31-Jan-19 13-Aug-19
5 3 31-Jan-24 13-Aug-19
6 3 13-Aug-20 13-Aug-19
7 3 13-Aug-21 13-Aug-19
8 3 13-Aug-22 13-Aug-19
9 3 13-Aug-23 13-Aug-19
10 3 13-Aug-24 13-Aug-19
> newdata
FI Lease.End.Date Distribution.Date correctdate
1 3 31-Jul-25 13-Aug-19 34
2 3 13-Aug-19 1
3 3 13-Aug-19 1
4 3 31-Jan-19 13-Aug-19 27
5 3 31-Jan-24 13-Aug-19 31
6 3 13-Aug-20 13-Aug-19 7
7 3 13-Aug-21 13-Aug-19 8
8 3 13-Aug-22 13-Aug-19 9
9 3 13-Aug-23 13-Aug-19 10
I want the correctdate column should have following values:
31-Jul-25
13-Aug-19
13-Aug-19
31-Jan-19
.
.
.
解决方案
尝试这个:
library(lubridate)
library(dplyr)
data <- data.frame(FI = c(3,3,3, 3,3), Lease.End.Date = c("31-Jul-25", "", "", "31-Jan-19", "31-Jan-24"), Distribution.Date = c("13-Aug-19", "13-Aug-19", "13-Aug-19", "13-Aug-19", "13-Aug-19"))
# -------------------------------------------------------------------------
typeof(data$Lease.End.Date)
#[1] "integer"
class(data$Lease.End.Date)
#[1] "factor"
typeof(data$Distribution.Date)
#"integer"
class(data$Distribution.Date)
#[1] "factor"
# -------------------------------------------------------------------------
# format the columns as date using lubridate date functions
# -------------------------------------------------------------------------
data$Distribution.Date <- dmy(data$Distribution.Date)
data$Lease.End.Date <- dmy(data$Lease.End.Date)
class(data$Distribution.Date)
#[1] "Date"
class(data$Lease.End.Date)
#[1] "Date"
# -------------------------------------------------------------------------
# the ifelse
newdata <- data %>%
select(FI, Lease.End.Date, Distribution.Date) %>%
mutate(correctdate = as.Date(ifelse(is.na(Lease.End.Date) ,Distribution.Date, Lease.End.Date), origin="1970-01-01"))
# -------------------------------------------------------------------------
# newdata
# FI Lease.End.Date Distribution.Date correctdate
# 1 3 2025-07-31 2019-08-13 2025-07-31
# 2 3 <NA> 2019-08-13 2019-08-13
# 3 3 <NA> 2019-08-13 2019-08-13
# 4 3 2019-01-31 2019-08-13 2019-01-31
# 5 3 2024-01-31 2019-08-13 2024-01-31
推荐阅读
- javascript - React + Redux,render() 没有返回任何内容
- apache-spark - 在 pyspark 中添加 mmlspark 包
- primefaces - 在 PrimeFaces 4.0 中没有 getter 的 p:dataTable 排序
- r - 将第一行添加到空 data.frame 时,行号不同(NA vs 1)
- java - Javafx 如何实现一个忙和等待的对话例程
- python - 在 Python 中使用开始/结束标记搜索/替换标头
- typescript - 从 VS Code 中的 Typescript 调试器中删除 Javascript 变量
- java - 如何仅获取从java中特定帐户发送或接收的电子邮件
- javascript - 在 Firebase 中设置或组织工作
- react-admin - React-admin 没有编辑列表