r - 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"
解决方案
矩阵不能包含 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
推荐阅读
- sql - Oracle 选择速度很快,但游标提取速度不快
- date - 根据条件从计算列中的前一行检索值
- r - 将表格行添加到树状图的标签
- python - 如何根据某些逻辑加入 2 个数据框
- powershell - PowerShell 更新嵌套值
- c++ - 为不应该获得未定义行为的事物获得未定义行为
- scala - Scala Spark:java.util.NoSuchElementException:找不到密钥:-1.0
- css - Flexbox 行:不根据内容增长?
- symfony - 我应该使用什么,语言环境路由或在我的 routes.yaml 中声明它?
- aframe - 360度图像的可怕质量