R:as.Date 提供矩阵中的数字,但日期为单个数字 - 差异?
R: as.Date delivers numbers in a matrix but with a single number a date - difference?
我的日期格式为 "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"
矩阵不能包含日期对象(也只能包含一种数据类型)。就这么简单。您将需要一个不同的数据结构,例如 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
我的日期格式为 "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"
矩阵不能包含日期对象(也只能包含一种数据类型)。就这么简单。您将需要一个不同的数据结构,例如 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