简体   繁体   English

如何删除 r 中的特定(并排)重复项?

[英]How to remove specific (side-by-side) duplicates in r?

Suppose I have the following string:假设我有以下字符串:

l1 = c(0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1)

and I only want to keep the "FIRST new 1", that is, my desire outcome of the above strong is:而我只想保留“FIRST new 1”,也就是我对上面强的渴望结果是:

l1 = c(0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)

I tried to shift and subtract the lists, whatever is not 1, set to 0;我试图移动和减去列表,无论不是 1,都设置为 0; but this way doesn't work.但这种方式行不通。

You may try (base R way)你可以试试(基础R方式)

x <- c(0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1)
y <- rle(x)
z<- cumsum(y$lengths)[y$values == 0] + 1
w <- rep(0, length(x))
w[z] <- 1
w

 [1] 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1

dplyr way dplyr方式

library(dplyr)
library(xts)
library(data.table)

x <- data.frame(
  l1 = c(0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1)
)
x %>%
  mutate(y = rleid(l1)) %>%
  group_by(y) %>%
  mutate(l1 = ifelse((y %% 2) == first(l1) & row_number(y)>1, 0, l1)) %>%
  ungroup %>%
  select(-y) %>%
  pull(l1)


 [1] 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1

Clumsy way笨拙的方式

bool IsNewOneAppeared = 0
for(int i;i<c.length;i++)
{
   if(IsNewOneAppeared )
   c[i]= 0;
   else if(c[i] equal 1)
   {
     keep 1;
     IsNewOneAppeared =1;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM