How to modify dates in R

R uses a date format different from the one we use in Spain for example, which can be DDMMYYYY or DDMMYYYY, etc., so we have to make a change in the format, which can be performed after loading the data, when the files are small, or during loading of the file, which is what to do when the files have a considerable size. The reason for doing so during charging is that the time the process takes  is determined by the component of our slower computer components, in this case, the hard disk, which is where our file is stored and, taking advantage of disk read time, our processor can be at the same time doing data modification processes. It is true that if we are talking about solid state drives the thing would be very different because it would not be so slow, but even so it is good practice to do things well.

How to modify dates in R

Having clear that the best thing to do is to modify the data using the loading time, I will show a very simple method to change the dates that are read from a csv in a data frame. The first thing to do is to create a new class with setClass() and then use setAs() to assign the format.

The code would be as follows:

In this case from is the data read from the csv. What you need to do now is to call the methods read.table() or read.csv() to transform it, and this is carried out through the colClasses, which is the parameter of these methods that is used to specify what type of data is read. I take this opportunity to explain that if during the reading we don’t indicate anything, R reads the data as factors. This will increase the loading time up to 5 times or even more, so it is a good choice to specify classes by colClasses.

Once the value has been assigned, we can load the file:

As you can see also have used the parameter stringsAsFactors = FALSE. In this way I tell R that the strings will have a character type.


Post Tagged with , , , , , , , ,

Comentarios y Respuestas

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">