从2001年到2018年,我每年都有几个.csv文件1,每个文件都有一个日期列。它们都是Excel中的m / d / y格式。当我用
将文件读入R时read.csv(x, stringsAsFactors = FALSE)
对于日期列,每个文件均已正确转换为y-m-d格式,但2018年除外,这使该文件保持相同的m / d / y格式。
由于m / d / y格式不兼容,当我尝试将日期带入Lubridate时,这是一个问题。
我不确定为什么只有2018年会出现此问题。
我尝试将日期复制并粘贴到数字excel格式中,然后使用read.csv将其导入R中。我已复制并以文本格式粘贴。我还打开了一个新的excel和csv文件,并将数据复制到这些文件中。我还手动输入了2018年日期,并使用read.csv导入了R。
可以通过以下方法解决此问题:
y <- read.csv(g, stringsAsFactors = FALSE) %>%
as.tibble()
y$date <- gsub("/", "-", y$date)
y$date <- parse_date_time(y$date, orders = c('mdy', 'ymd'))
y$date <- as_date(y$date)
但是我发现这令人感到不安,并且想知道为什么excel只在2018年这样做,以及其他人是否遇到过这种情况。
这是我的2001.csv文件在
之后的样子的示例y <- read.csv(x, stringsAsFactors = FALSE) %>%
as.tibble()
y
# # A tibble: 24 x 4
# date species Site_Code number
# <chr> <chr> <int> <int>
# 1 2001-08-11 WN 23 0
# 2 2001-10-12 WN 23 0
# 3 2001-01-11 EEE 27 0
这是用与上面相同的代码读取后的2018.csv文件的样子:
# A tibble: 84 x 4
date species Site_Code number
<chr> <chr> <int> <int>
1 4/16/2018 EEE 23 0
2 4/30/2018 EEE 23 1
3 5/7/2018 EEE 23 0
没有错误消息生成
答案 0 :(得分:0)
您的列仍然是char
,而不是date
。您可以使用str(y)
进行验证,这就是<chr>
中tibble
标头试图告诉您的内容。执行以下操作,以将其显式转换为lubridate
日期格式。您的y
动作示例。
y <- read.csv(x, stringsAsFactors = FALSE) %>%
as.tibble()
# str(y)
#Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 4 variables:
# $ date : chr "4/16/2018" "4/30/2018" "5/7/2018"
# $ species : chr "EEE" "EEE" "EEE"
# $ Stite_Code: num 23 23 23
# $ number : num 0 1 0
# date col is still chr
# do the following
y$date <- mdy(y$date)
str(y)
# Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3 obs. of 4 variables:
# $ date : Date, format: "2018-04-16" "2018-04-30" ...
# $ species : chr "EEE" "EEE" "EEE"
# $ Stite_Code: num 23 23 23
# $ number : num 0 1 0
# Now date is Date format
y <-structure(list(date = c("4/16/2018", "4/30/2018", "5/7/2018"),
species = c("EEE", "EEE", "EEE"), Stite_Code = c(23, 23,
23), number = c(0, 1, 0)), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))