将标题中的日期从 Excel 转换/维护到 R
•浏览 1
Convert/Maintain Dates in Header from Excel to R
我有一个 Excel 电子表格,标题中有日期。我想将电子表格导入 R,大概使用 read.xlsx() 函数。但是,日期从 Excel 转换为内部值的字符串,前面带有 "X"。我希望将日期保留为日期类,或将字符串转换为日期。我知道我可以使用 as.Date() 如果日期至少是一种格式,或者是从指定来源开始的天数,但它有 "X"。
非常感谢您的帮助。
例如。
excel 电子表格"Practice"
Sample 09-Jul 10-Jul 11-Jul
1 3 10 2
2 5 0
3 1 0 0practice<-read.xlsx("Practice.xlsx")
Sample X42925 X42926 X42927
1 1 3 10 2
2 2 5 0 NA
3 3 1 0 0
practice2=gather(practice,Date,value,-Sample,na.rm=TRUE)
Sample Date value
1 1 X42925 3
2 2 X42925 5
3 3 X42925 1
4 1 X42926 10
5 2 X42926 0
6 3 X42926 0
7 1 X42927 2
9 3 X42927 0
practice2$Date=as.Date(practice2$Date)
Error in charToDate(x) :
character string is not in a standard unambiguous formatdates <- as.numeric(substr(practice2$Dates, 2, nchar(practice2$Dates)))
practice2$Dates <- as.Date(dates, origin = '1899-12-30')
然后在 R:
Sample 09-Jul 10-Jul 11-Jul
1 3 10 2
2 5 0
3 1 0 0practice<-read.xlsx("Practice.xlsx")
Sample X42925 X42926 X42927
1 1 3 10 2
2 2 5 0 NA
3 3 1 0 0
practice2=gather(practice,Date,value,-Sample,na.rm=TRUE)
Sample Date value
1 1 X42925 3
2 2 X42925 5
3 3 X42925 1
4 1 X42926 10
5 2 X42926 0
6 3 X42926 0
7 1 X42927 2
9 3 X42927 0
practice2$Date=as.Date(practice2$Date)
Error in charToDate(x) :
character string is not in a standard unambiguous formatdates <- as.numeric(substr(practice2$Dates, 2, nchar(practice2$Dates)))
practice2$Dates <- as.Date(dates, origin = '1899-12-30')
值 X42925 是 Excel 序列日期,大致对应于 1900 年 1 月 1 日之后 42925 天的日期。我们可以使用具有适当来源的 as.Date 将这些序列日期转换为 R 日期。
您应该能够使用以下内容转换您的日期列。这假定以 X 为前缀的日期是作为文本读入的。
Sample 09-Jul 10-Jul 11-Jul
1 3 10 2
2 5 0
3 1 0 0practice<-read.xlsx("Practice.xlsx")
Sample X42925 X42926 X42927
1 1 3 10 2
2 2 5 0 NA
3 3 1 0 0
practice2=gather(practice,Date,value,-Sample,na.rm=TRUE)
Sample Date value
1 1 X42925 3
2 2 X42925 5
3 3 X42925 1
4 1 X42926 10
5 2 X42926 0
6 3 X42926 0
7 1 X42927 2
9 3 X42927 0
practice2$Date=as.Date(practice2$Date)
Error in charToDate(x) :
character string is not in a standard unambiguous formatdates <- as.numeric(substr(practice2$Dates, 2, nchar(practice2$Dates)))
practice2$Dates <- as.Date(dates, origin = '1899-12-30')
演示
尝试将 Excel 文件另存为 .csv。这会将您的数据和日期转换为纯文本,应该可以毫无问题地导入 R。
或者,尝试以下方法之一:
http://www.milanor.net/blog/read-excel-files-from-r/
祝你好运!