首页 > 解决方案 > R:as.Date 以矩阵形式提供数字,但日期只有一个数字 - 差异?

问题描述

我有格式为“X12.11.1985”的日期,如果我使用该as.date()函数将其转换为 a matrix,它会提供一个数字。如果我as.date()只使用一个日期,那么它会提供一个真实的日期。

为什么as.Date()我的代码中函数的结果不同?

非常感谢!

最小的例子:

 col1 = c("X01.03.1988","X05.05.1995","X11.11.1990")
 col2 = c(1,3,2)
 mat = cbind(col1,col2)      
 mat[,'col1'] <- as.Date(mat[,'col1'], format='X%d.%m.%Y')
 mat <- mat[order(as.numeric(mat[,'col1'])),]
 mat #Result is ordered correct but as.Date converts the dates to numbers like "6634"

 as.Date("X01.03.1988",format='X%d.%m.%Y') #Converts the date to a date like "1988-03-01"

标签: rdateas.date

解决方案


矩阵不能包含 Date 对象(也只能包含一种数据类型)。就这么简单。您将需要不同的数据结构,例如 data.frame。

col1 = c("X01.03.1988","X05.05.1995","X11.11.1990")
col2 = c(1,3,2)
mat = data.frame(col1,col2) #correct data structure      
mat[,'col1'] <- as.Date(mat[,'col1'], format='X%d.%m.%Y')
mat <- mat[order(as.numeric(mat[,'col1'])),]
mat 
#        col1 col2
#1 1988-03-01    1
#3 1990-11-11    2
#2 1995-05-05    3

推荐阅读