How to remove repeated numbers in sequence in R data frame column?


To remove repeated numbers in sequence in R data frame column, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use diff function and subsetting with single square brackets to remove repeated numbers in sequence.

Example 1

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(25,3)
df<-data.frame(x)
df

Output

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

   x
1  4
2  3
3  6
4  5
5  4
6  3
7  3
8  4
9  4
10 4
11 1
12 3
13 4
14 2
15 3
16 0
17 0
18 4
19 4
20 2
21 3
22 2
23 2
24 2
25 2

Remove repeated numbers in sequence

Using diff function and subsetting with single square brackets to remove repeated numbers in sequence from column x of data frame df −

x<-rpois(25,3)
df<-data.frame(x)
df$x[c(1,diff(df$x))!=0]

Output

[1] 1 3 4 6 5 2 3 4 1 5 4 3 0 1 4 3 2 7 3 4 1 3 4

Example 2

Create the data frame

Let’s create a data frame as shown below −

y<-sample(1:4,25,replace=TRUE)
dat<-data.frame(y)
dat

Output

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

   y
1  3
2  3
3  3
4  1
5  1
6  3
7  1
8  1
9  3
10 4
11 1
12 2
13 2
14 2
15 4
16 1
17 2
18 2
19 4
20 3
21 2
22 1
23 1
24 3
25 2

Remove repeated numbers in sequence

Using diff function and subsetting with single square brackets to remove repeated numbers in sequence from column y of data frame dat −

y<-sample(1:4,25,replace=TRUE)
dat<-data.frame(y)
dat$y[c(1,diff(dat$y))!=0]

Output

[1] 3 1 3 1 3 4 1 2 4 1 2 4 3 2 1 3 2

Updated on: 11-Nov-2021

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements