Remove i + 1st member if re-completion

Let's say we have the following data

A <- c(1,2,2,2,3,4,8,6,6,1,2,3,4)
B <- c(1,2,3,4,5,1,2,3,4,5,1,2,3)

data <- data.frame(A,B)

      

How do I write a function such that for A

, if we have the same value in position i+1th

, then the reoccupation line is removed.

So the output should look like

data.frame(c(1,2,3,4,8,6,1,2,3,4), c(1,2,5,1,2,3,5,1,2,3))

      

My best guess is to use the for statement, however I have no experience with these

+3


source to share


4 answers


You may try



  data[c(TRUE, data[-1,1]!= data[-nrow(data), 1]),]

      

+4


source


Another option, dplyr

-esque:



library(dplyr)
dat1 <- data.frame(A=c(1,2,2,2,3,4,8,6,6,1,2,3,4),
                   B=c(1,2,3,4,5,1,2,3,4,5,1,2,3))
dat1 %>% filter(A != lag(A, default=FALSE))
##    A B
## 1  1 1
## 2  2 2
## 3  3 5
## 4  4 1
## 5  8 2
## 6  6 3
## 7  1 5
## 8  2 1
## 9  3 2
## 10 4 3

      

+3


source


using diff, which computes pairwise differences with a delay of 1:

data[c( TRUE, diff(data[,1]) != 0), ]

      

output:

   A B
1  1 1
2  2 2
5  3 5
6  4 1
7  8 2
8  6 3
10 1 5
11 2 1
12 3 2
13 4 3

      

+1


source


Using rle

A <- c(1,2,2,2,3,4,8,6,6,1,2,3,4)
B <- c(1,2,3,4,5,1,2,3,4,5,1,2,3)

data <- data.frame(A,B)

X <- rle(data$A)
Y <- cumsum(c(1, X$lengths[-length(X$lengths)]))
View(data[Y, ])


row.names   A   B
1   1   1   1
2   2   2   2
3   5   3   5
4   6   4   1
5   7   8   2
6   8   6   3
7   10  1   5
8   11  2   1
9   12  3   2
10  13  4   3

      

0


source







All Articles