【问题标题】:R: Incorrect Dates After Using read.csvR:使用 read.csv 后日期不正确
【发布时间】:2017-02-07 23:42:43
【问题描述】:

这让我很难过。我尝试了几种我在 SO 和其他地方的其他地方找到的解决方案,但无济于事。最接近我的问题的似乎是这个问题:

Convert factor to date object R without NA

我正在尝试读取包含日期信息的 .csv。包含日期的列作为一个因素读入。当我将其转换为“日期”类时,日期会出现乱码。下面是一个简单的 .csv 文件的 Dropbox 链接,可以让您重现问题:

https://www.dropbox.com/s/07xuuy6pmw3qctt/dates.csv?dl=0

代码:

dates <- read.csv("dates.csv")


dates
        Name      Date
1   Person 1  1/1/2000
2   Person 2  2/1/2001
3   Person 3  3/1/2002
4   Person 4  4/1/2003
5   Person 5  5/1/2004
6   Person 6  6/1/2005
7   Person 7  7/1/2006
8   Person 8  8/1/2007
9   Person 9  9/1/2008
10 Person 10 10/1/2009



dates$Date <- as.Date(dates$Date, "%m/%d/%y")
dates

dates
        Name       Date
1   Person 1 2020-01-01
2   Person 2 2020-02-01
3   Person 3 2020-03-01
4   Person 4 2020-04-01
5   Person 5 2020-05-01
6   Person 6 2020-06-01
7   Person 7 2020-07-01
8   Person 8 2020-08-01
9   Person 9 2020-09-01
10 Person 10 2020-10-01

所有年份都更改为 2020 年,此时它们应以 2001 年开始并以 2009 年结束。如何在不错误更改值的情况下将日期显示为日期?

【问题讨论】:

  • 是的,我得到了同样的结果。
  • read.csv无关。您只是错误地使用了as.Date。请先仔细阅读?strptime。我不知道您的数据中首先出现的是哪一天或月份,但您绝对应该将%y 更改为%Y。附带说明一下,在运行整个代码块后指责单个函数而不检查每个步骤的作用是非常愚蠢的。
  • 您能否提供一个您尝试转换为日期的原始值的样本?
  • @LloydChristmas,编辑显示读入后值如何打印。
  • 换句话说as.Date(date$Date, "%m/%d/%Y")as.Date(date$Date, "%d/%m/%Y")(取决于月份或日期是否在前)

标签: r


【解决方案1】:

试试这个:

dbName <- "https://dl.dropboxusercontent.com/s//07xuuy6pmw3qctt/dates.csv” #your file

读作data.frame

df <- read.csv(dbName,header=TRUE,stringsAsFactors=F)
df$Date <- as.Date(df$Date,format ='%m/%d/%Y' )
head(df)
        Name       Date
1   Person 1 2000-01-01
2   Person 2 2001-02-01
3   Person 3 2002-03-01
4   Person 4 2003-04-01
5   Person 5 2004-05-01
6   Person 6 2005-06-01

将文件导入为xts-object:

dbFile <- as.xts(read.zoo(dbName,sep=',',header=TRUE,index.column = 2,format='%m/%d/%Y',stringsAsFactors=F))
names(dbFile) <- "name"

head(dbFile)
           name       
2000-01-01 "Person 1" 
2001-02-01 "Person 2" 
2002-03-01 "Person 3" 
2003-04-01 "Person 4" 
2004-05-01 "Person 5" 
2005-06-01 "Person 6" 

【讨论】:

  • 谢谢,这行得通!我错过的关键是,一旦你错误地使用了 'format ='%m/%d/%y',你就必须回到第一方的 'format ='%m/%d/%你要工作。
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
相关资源
最近更新 更多