[英]R: readxl and date format
I read in an excel file, where 1 column contains dates in different format: excel format (eg 43596) and text (eg "01.01.2020").我读了一个 excel 文件,其中 1 列包含不同格式的日期:excel 格式(例如 43596)和文本(例如“01.01.2020”)。 To convert excel format one can use
as.Date(as.numeric(df$date), origin = "1899-12-30")
to convert text one can use as.Date(df$date, format = "%d.%m.%Y")
These work for individual values, but when I try ifelse as:要转换 excel 格式,可以使用
as.Date(as.numeric(df$date), origin = "1899-12-30")
转换文本,可以使用as.Date(df$date, format = "%d.%m.%Y")
这些适用于单个值,但是当我尝试 ifelse 时:
df$date <- ifelse(length(df$date)==5,
as.Date(as.numeric(df$date), origin = "1899-12-30"),
as.Date(df$date, format = "%d.%m.%Y"))
or a for loop:或 for 循环:
for (i in length(x)) {
if(nchar(x[i])==5) {
y[i] <- as.Date(as.numeric(x[i]), origin = "1899-12-30")
} else {x[i] <- as.Date(x[i], , format = "%d.%m.%Y"))}
} print(x)
It does not work because of:它不起作用,因为:
"character string is not in a standard unambiguous format"
“字符串不是标准的明确格式”
Maybe you could advice a better solution to convert/ replace different date formats in the appropriate one?也许您可以建议一种更好的解决方案来转换/替换适当的不同日期格式?
I have 2 solutions for it.我有两个解决方案。
> df <- tibble(date = c("01.01.2020","43596"))
>
> df$date <- as.Date(ifelse(nchar(df$date)==5,
+ as.Date(as.numeric(df$date), origin = "1899-12-30"),
+ as.Date(df$date, format = "%d.%m.%Y")), origin = "1970-01-01")
Warning message:
In as.Date(as.numeric(df$date), origin = "1899-12-30") :
NAs introducidos por coerción
>
> df$date
[1] "2020-01-01" "2019-05-11"
>
read_csv()
function from readr
package.readr
器 package 的read_csv()
function。 That solves everything !!!!You could use sapply
to apply ifelse
to each value:您可以使用
sapply
将ifelse
应用于每个值:
df$date <- as.Date(sapply(df$date,function(date) ifelse(nchar(date)==5,
as.Date(as.numeric(date), origin = "1899-12-30"),
as.Date(date, format = "%d.%m.%Y"))),
origin="1970-01-01")
df
# A tibble: 6 x 2
contract date
<dbl> <date>
1 231429 2019-05-11
2 231437 2020-01-07
3 231449 2021-01-01
4 231459 2020-03-03
5 231463 2020-10-27
6 231466 2011-03-17
A tidyverse
solution using rowwise
使用
rowwise
的tidyverse
解决方案
library(dplyr)
library(lubridate)
df %>%
rowwise() %>%
mutate(date_new=as.Date(ifelse(grepl("\\.",date),
as.character(dmy(date)),
as.character(as.Date(as.numeric(date), origin="1899-12-30"))))) %>%
ungroup()
# A tibble: 6 × 3
contract date date_new
<dbl> <chr> <date>
1 231429 43596 2019-05-11
2 231437 07.01.2020 2020-01-07
3 231449 01.01.2021 2021-01-01
4 231459 03.03.2020 2020-03-03
5 231463 44131 2020-10-27
6 231466 40619 2011-03-17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.