user2894356
user2894356

Reputation: 139

R: as.Date delivers numbers in a matrix but with a single number a date - difference?

I have dates in the format "X12.11.1985" and if I use the as.date() function to convert it on a matrix, it delivers a single number. If I use as.date() with just one single date, then it delivers a real date.

Why is the result of the as.Date() function different in my code?

Thank you very much!

Minimal example:

 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"

Upvotes: 0

Views: 168

Answers (1)

Roland
Roland

Reputation: 132706

A matrix cannot contain Date objects (and also can only contain one data type). It's as simple as that. You'll need a different data structure such as a 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

Upvotes: 2

Related Questions