How to avoid formatted date values ​​converted to numeric when assigned to a matrix or data frame?

I had a problem that I don’t understand, and I could not find the answer to this problem on this website (I continue to answer questions about how to convert dates to numeric or vice versa, but this is exactly what I do not want know).

The problem is that R converts values ​​that are formatted as a date (for example, "20-09-1992") to numeric values ​​when you assign them to a matrix or data frame. For example, we have "20-09-1992" with the date format, we checked this with class() .

 as.Date("20-09-1992", format = "%d-%m-%Y") class(as.Date("20-09-1992", format = "%d-%m-%Y")) 

Now we assign this value to the matrix, figuratively called the Matrix:

 Matrix <- matrix(NA,1,1) Matrix[1,1] <- as.Date("20-09-1992", format = "%d-%m-%Y") Matrix[1,1] class(Matrix[1,1]) 

Suddenly, the previous date, formatted "20-09-1992", became a numeric value with a value of 8298. I do not want a numeric value with a value of 8298, I need a date that looks like "20-09-1992", in a date format.

So I was wondering if R just works, and we are not allowed to assign dates for matrices and data frames (somehow I managed to have dates in other matrices / data frames, but it hits me, why those other times were different)? Is there a special method for assigning dates to data frames and matrices that I missed and could not deduce from previous (somehow successful) attempts to assign dates to data frames / matrices?

+5
source share
2 answers

I do not think you can store dates in a matrix. Use a data frame or data table. If you need to store dates in a matrix, you can use a list matrix.

 Matrix <- matrix(NA,1,1) Matrix[1,1] <- as.list(as.Date("20-09-1992", format = "%d-%m-%Y"),1) Matrix [[1]] [1] "1992-09-20" 

Edited: I also just re-read that you had this problem with the data frame. I'm not sure why.

 mydate<-as.Date("20-09-1992", format = "%d-%m-%Y") mydf<-data.frame(mydate) mydf mydate 1 1992-09-20 

Edited: It was a learning experience for me with R and dates. Apparently, the date you specified was converted to the number of days from the moment it occurred. The origin is defined as January 1, 1970. To convert this back to date format at some point

 Matrix [,1] [1,] 8298 as.Date(Matrix, origin ="1970-01-01") [1] "1992-09-20" 
+4
source

try this: first specify your date vector and then use

 rownames(mat) <- as.character(date_vector) 

dates will be displayed as text.

0
source

Source: https://habr.com/ru/post/1262927/


All Articles