How to delete repeated rows in xts object in R?


To delete repeated rows in xts object in R, we can follow the below steps −

  • First of all, create an xts object.

  • Then, use duplicated and index function to delete repeated rows.

Example

Create the xts object

Let’s create an xts object as shown below −

library(xts)
T<- xts(1:40,rep(seq.Date(Sys.Date(),by="day",length=10),each=4))
T

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     [,1]
2021-09-24  1
2021-09-24  2
2021-09-24  3
2021-09-24  4
2021-09-25  5
2021-09-25  6
2021-09-25  7
2021-09-25  8
2021-09-26  9
2021-09-26 10
2021-09-26 11
2021-09-26 12
2021-09-27 13
2021-09-27 14
2021-09-27 15
2021-09-27 16
2021-09-28 17
2021-09-28 18
2021-09-28 19
2021-09-28 20
2021-09-29 21
2021-09-29 22
2021-09-29 23
2021-09-29 24
2021-09-30 25
2021-09-30 26
2021-09-30 27
2021-09-30 28
2021-10-01 29
2021-10-01 30
2021-10-01 31
2021-10-01 32
2021-10-02 33
2021-10-02 34
2021-10-02 35
2021-10-02 36
2021-10-03 37
2021-10-03 38
2021-10-03 39
2021-10-03 40

Delete duplicated rows

Using duplicated and index function to delete repeated rows in xts object T −

library(xts)
T<- xts(1:40,rep(seq.Date(Sys.Date(),by="day",length=10),each=4))
T[!duplicated(index(T)), ]

Output

    [,1]
2021-09-24  1
2021-09-25  5
2021-09-26  9
2021-09-27 13
2021-09-28 17
2021-09-29 21
2021-09-30 25
2021-10-01 29
2021-10-02 33
2021-10-03 37

Updated on: 15-Nov-2021

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements