我的日期格式为"X12.11.1985",如果我使用as.date()
函数在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"
矩阵不能包含 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