我正在尝试将日期信息从.csv文件转换为R中的日期格式,以便创建两周的时间间隔来对数据进行分类。但是,当使用as.Date时,它仅在某些日期正常工作,其余日期为NA。我已经尝试在excel中编辑日期单元格的格式,我尝试从头开始重写excel中的每个日期单元格。我试过改变我的语言环境。我已经尝试了所有可以找到的在线解决方案。请帮忙!
> lions <- read.csv("Lions_30m.csv")
> dates<-as.character(lions$Date)
> typeof(dates)
[1] "character"
> dates
[1] "5/1/2017" "5/9/2017" "5/21/2017" "4/17/2017" "4/21/2017" "5/12/2017"
"3/27/2017" "3/13/2017"
[9] "4/10/2017" "4/26/2017" "4/23/2017" "3/7/2017" "5/28/2017" "4/27/2017"
"5/16/2017" "4/5/2017"
[17] "2/16/2017" "2/18/2017" "4/26/2017" "2/26/2017" "2/26/2017" "5/18/2017"
"3/4/2017" "4/14/2017"
[25] "3/3/2017" "3/31/2017" "3/11/2017" "3/19/2017" "3/22/2017" "3/23/2017"
"3/25/2017" "4/13/2017"
[33] "4/14/2017" "4/15/2017" "4/17/2017" "4/19/2017" "4/23/2017" "4/29/2017"
"5/15/2017" "3/26/2017"
[41] "5/6/2017"
> date <-as.Date(dates, format='%d/%m/%Y')
> date
[1] "2017-01-05" "2017-09-05" NA NA NA "2017-12-05" NA
[8] NA "2017-10-04" NA NA "2017-07-03" NA NA
[15] NA "2017-05-04" NA NA NA NA NA
[22] NA "2017-04-03" NA "2017-03-03" NA "2017-11-03" NA
[29] NA NA NA NA NA NA NA
[36] NA NA NA NA NA "2017-06-05"
答案 0 :(得分:2)
你想要%m/%d/%Y
,而不是%d/%m/%Y
,除非你住在一个每年有21个月的奇怪国家......
答案 1 :(得分:1)
我们也可以使用anytime
自动执行此操作,该library(anytime)
anydate(c("4/26/2017", "2/26/2017", "2/26/2017" ))
#[1] "2017-04-26" "2017-02-26" "2017-02-26"
根据输入
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
答案 2 :(得分:1)
dates <- c("5/1/2017", "5/9/2017", "5/21/2017", "4/17/2017", "4/21/2017", "5/12/2017",
"3/27/2017", "3/13/2017", "4/10/2017", "4/26/2017", "4/23/2017", "3/7/2017",
"5/28/2017", "4/27/2017", "5/16/2017", "4/5/2017", "2/16/2017", "2/18/2017",
"4/26/2017", "2/26/2017", "2/26/2017", "5/18/2017", "3/4/2017", "4/14/2017",
"3/3/2017", "3/31/2017", "3/11/2017", "3/19/2017", "3/22/2017", "3/23/2017",
"3/25/2017", "4/13/2017", "4/14/2017", "4/15/2017", "4/17/2017", "4/19/2017",
"4/23/2017", "4/29/2017", "5/15/2017", "3/26/2017", "5/6/2017")
使用class()
查看它是什么,所以说话
class(dates)
#> [1] "character"
as_date_dates <- as.Date(dates, "%m/%d/%Y")
class(as_date_dates)
#> [1] "Date"
或以lubridate方式避免%m/%d/%Y
- %d/%m/%Y
混淆。 Kinda same idea akrun is going with,
# install.packages(c("lubridate"), dependencies = TRUE)
library(lubridate)
as_lubridate_dates <- mdy(dates)
class(as_lubridate_dates)
#> [1] "Date"